Reputation: 5055
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
?
Upvotes: 2
Views: 1923
Reputation: 169200
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.
Upvotes: 2