views:

121

answers:

0

I have a Collection of Model-objects in my ViewModel. I would like to be able to bind a TabControl to these and use a DataTemplate to extract the information from the Model-objects. When I try to do this I get the errormessage: Unable to cast object of type Model to object of type TabItem. After spending some time looking for a solution I found the following:

  1. The Silverlight TabControl is broken. Use a combination of ListBox and ContentControl to mimic the behaviour of a TabControl. (Means that I have to skin the ListBox to look like a TabControl)

  2. TabControl does not override PrepareContainerForItemOverride and the solution is to make a Converter. (Not so good because I then need to specify the type of the convertee in the Converter)

Anyone know any better solution?

XAML

<sdk:TabControl ItemsSource="{Binding Items, ElementName=MyControl}">
        <sdk:TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </sdk:TabControl.ItemTemplate>
    </sdk:TabControl>

C#

public ObservableCollection<Model> Items { get; set; }

public ViewModel()

    Items = new ObservableCollection<Model>{
        new Model { Name = "1"},
        new Model { Name = "2"},
        new Model { Name = "3"},
        new Model { Name = "4"}
    };
}

Suggested Converter:

public class TabConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        List<TabSource> source = value as List<TabSource>;
        if (source != null)
        {
            List<TabItem> result = new List<TabItem>();
            foreach (TabSource tab in source)
            {
                result.Add(new TabItem()
                {
                    Header = tab.Header,
                    Content = tab.Content
                });
            }
            return result;
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}