WPF MVVM: Binding a different ViewModel to each TabItem?
You can indeed add the view models for your tabs to a main view model. You can then bind to the child view models in the XAML for your tabs.
Say that you have three viewmodels: MainViewModel
, Tab1ViewModel
, and Tab2ViewModel
. On your MainViewModel
you keep a collection of your tab viewmodels:
class MainViewModel
{
ObservableCollection<object> _children;
public MainViewModel()
{
_children = new ObservableCollection<object>();
_children.Add(new Tab1ViewModel());
_children.Add(new Tab2ViewModel());
}
public ObservableCollection<object> Children { get { return _children; } }
}
After setting the DataContext
of your main window to your MainViewModel
you can bind the DataContext
of your tabs by referencing the Children
property:
<TabControl>
<TabItem DataContext="{Binding Children[0]}" x:Name="Tab1" Header="Tab1" >
<!-- Tab content -->
</TabItem>
<TabItem DataContext="{Binding Children[1]}" x:Name="Tab2" Header="Tab2" >
<!-- Tab content -->
</TabItem>
</TabControl>
class MainViewModel
{
ObservableCollection<object> _children;
public MainViewModel()
{
_children = new ObservableCollection<object>();
_children.Add(new Tab1ViewModel());
_children.Add(new Tab2ViewModel());
}
public ObservableCollection<object> Children { get { return _children; } }
}
Now in XAML bind the Children to ItemsSource. It will generate each Tab for every viewmodel we have added into the observable collection
<TabControl ItemsSource="{Binding Children}"/>