TabControl problem with ItemSource property RRS feed

  • General discussion

  • It seems that the new Silverlight 2 beta 2 TabControl does not support DataBinding via ItemSource property. Here is my problem : I have a collection of a business object. When I set the collection as ItemSource of the TabControl I get an InvalidCastException: Unable to cast object of type "My business object type" to "System.Control.TabItem.".

    Any idea? Is it a bug?


    Monday, June 9, 2008 10:42 PM

All replies

  • I would say it is a bug

    Tuesday, June 10, 2008 4:53 AM
  • Hi:

      Please try this:

      List<TabItem> array = new List<TabItem>();
            public Page()

                for (int i = 0; i <3; i++)

                    TabItem c = new TabItem();
                    StackPanel sp = new StackPanel();
                    TextBlock tb= new TextBlock();
                    tb.Text = i.ToString();
                    c.Content = sp;

                this.TabControl1.ItemsSource = array;



    Tuesday, June 10, 2008 11:27 PM
  • This looks like a work around, will this be fixed in RTM

    Wednesday, June 11, 2008 11:42 AM
  • Thanks for your answer Allen. I understand your answer and I already implemented a workaround similar to the solution that you proposed. But what I really want is to set my buisness object collection directly to the ItemSource of the TabControl so that each TabItem has automatically one of the buisness object instance as DataContext. With a ListBox for instance, I can set a collection of buisness object as ItemSource with an ItemTemplate that determine the UI for each item.


    Wednesday, June 11, 2008 10:42 PM
  • Hi,

    Because the Tab Control doesn't seem to support templates, it casts each item in your business object collection to System.Control.TabItem, hence you get the invalid cast exception.

    I have gotten around this by using a ValueConverter to implement a template in code:

    public class TabValueConverter : IValueConverter
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    List<TabItem> tabs=new List<TabItem>();
    foreach (BussinessObject item in (IEnumerable)value)

    TabItem tabUi = new TabItem();
    tabUi.Header = item.Name;
    tabUi.Content = ....create FrameWorkElement here to act as template.....

    return tabs;
    }public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    return null;


    Then reference it in XAML as follows:

    <local:FormTabValueConverter x:Name="ConvertToTab"/>

    <System_Windows_Controls:TabControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0" ItemsSource="{Binding Mode=OneWay, Converter={StaticResource ConvertToTab}}"

    Hope this helps,


    Friday, July 25, 2008 1:42 PM