tags:

views:

18

answers:

2

I have an ObservableCollection<Item> and I want to set it as the ItemsSource property of a TabControl. The Item class contains a Property TabItem that returns a System.Windows.Controls.TabItem. I want the TabControl to display the TabItems from the collection.

(In reality, there are lots of properties on the "Item" class.)

Code:

Item class:

public class Item
{
    public Item(TabItem tabItem)
    {
        this.TabItem = tabItem;
    }

    public TabItem TabItem { get; private set; }
}

TabControl XAML:

<TabControl x:Name="tabControl" />

Code behind:

this.tabControl.ItemsSource = new ObservableCollection<Item>()
{
    new Item(new TabItem(){Header = "TabItem 1 Header", Content = "TabItem 1 Content"}),
    new Item(new TabItem(){Header = "TabItem 2 Header", Content = "TabItem 2 Content"}),
    new Item(new TabItem(){Header = "TabItem 3 Header", Content = "TabItem 3 Content"}),
    new Item(new TabItem(){Header = "TabItem 4 Header", Content = "TabItem 4 Content"}),
    new Item(new TabItem(){Header = "TabItem 5 Header", Content = "TabItem 5 Content"}),
};

I've tried setting the TabControl's DisplayMemberPath to "TabItem" but that didn't work. I've been unable to get ItemTemplate and ContentTemplate to actually display the TabItem (I could bind to the Header and Content of the TabItems respectively, but that's not what I want).

If I were using a ObservableCollection<TabItem> and set it to ItemsSource it displays the TabItems as you would expect, yet I can't get it to work with this additional step.

What am I doing wrong? Is there a way to get this to work?

A: 

I think you should use style to set the content. You have ItemContainerStyle which would help as stated here : http://stackoverflow.com/questions/686074/wpf-tabcontrol-databinding

:)

abhishek
A: 

I think if you got rid of the Item class and just added TabItems, your code would work. By doing it that way however, your limiting what you can do with the styling of the TabItems.

mdm20
I mentioned at the end of my question that that does work. But, I already have the "Item" class that is actually a lot more complex than the one used here, and I need to keep it around. So, I can't do that.
Ashley
Just bind to the item class. The tabcontrol will automatically add a tabitem for each item in your collection. then you just have to change the tabitem style to bind the header and content to some property in your item class.
mdm20
That's very similar to what I already mentioned I tried in the question using ItemTemplate and ContentTemplate. Unfortunately, either way, I still lose the changes to the TabItems themselves. But, I think I'm going to have to do it that way anyways, and just add a workaround to get the changes I need to the TabItems.
Ashley