简体   繁体   中英

Binding collection of viewmodels to WPF MVVM TabControl

I have a collection of ViewModels I want to bind to the ItemsSource property of a TabControl and be able to add/remove them dynamically, so have implemented as an Observable<TabViewModel> .

However the TabControl seems to expect types which inherit from TabItem , which is a visual control object. I don't want my ViewModels to inherit from TabItem as that means they then need to be bound to a visual implementation and also all tests need to run as STA.

How can I bind a collection of ViewModels to populate the headers and content of a tab control without depending on the TabItem object? Ie just using styles and templates I suppose based on the ViewModel type. Just like if you had a ListBox and wanted the items to render directly from viewmodel instances, with a specific template, that is easy to do by overriding the ItemTemplate property.

How do I do this with a TabControl without using TabItem ?

How can I bind a collection of ViewModels to populate the headers and content of a tab control without depending on the TabItem object?

Try this:

View:

<TabControl ItemsSource="{Binding Items}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Header}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Content}" />
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

View Model:

public class TabViewModel
{
    public TabViewModel()
    {
        Items = new ObservableCollection<Item>()
        {
            new Item { Header = "a", Content = "..." },
            new Item { Header = "b", Content = "..." },
            new Item { Header = "c", Content = "..." },
        };
    }

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

Item is a POCO class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM