0
votes

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?

2

2 Answers

0
votes

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.

0
votes

I think you should use style to set the content. You have ItemContainerStyle which would help as stated here : WPF TabControl Databinding

:)