In WPF, I have one Window containing a TabControl with four TabItems. Each TabItem has a Grid:
<TabItem Header="Input" Name="tabItem1">
<Grid></Grid>
</TabItem>
In my codebehind I need to specify a datacontext pointing to a ViewModel. Rather than having one ViewModel to handle all four tabs, I would like a ViewModel for each Tab. This would mean having different DataContexts for each time.
Is there a way to achieve this in a clean way?
You can set
DataContext
in XAML only by declaring instance in XAML only and bind DataContext to that instance.But since you asked for cleaner way, so ideal would be to bind
ItemsSource
of TabControl to collection of ViewModels so that all tabItems automatically have different DataContext.First create
DummyViewModel
and haveObservableCollection<DummyViewModel>
collection in your main window ViewModel.and bind with collection in XAML like this:
ItemTemplate is defined for header of tab items and ContentTemplate is defined for content of individual tabItems.
Four tab items will be created with each tab item DataContext is set to separate instance of DummyViewModel.
SnapShot: