I have a main window with a tab control containing 2 tabItem
s:
I currently have 1 ViewModel
which services Tab1 & Tab2. This ViewModel
is becoming a little bloated with blurred SOC. I want to split the logic into 2 viewmodels: ViewModel 1 & ViewModel2. My understanding is that you can set the Main Window DataContext
to a Base ViewModel which holds a collection of ViewModels & then you can assert each TabItem to a different ViewModel.
The example's I've seen of these base ViewModels expose an ObservableCOllection like so:
private ObservableCollection<ViewModel1> _viewModelCollection
Public Observable Collection<ViewModel1> ViewModelCollection
{
get { return _viewModelCollection; }
set
{
_viewModelCollection = value;
OnPropertyChanged("ViewModelCollection");
}
}
public BaseViewModel()
{
ViewModelCollection = new ObservableCollection<ViewModel1>();
ViewModelCollection.Add(new ViewModel1(Tab1);
ViewModelCollection.Add(new ViewModel1(Tab2);
}
But how do I assign a different ViewModel to each TabItem? I would want Tab1= ViewModel1 & Tab2=ViewModel2?
Now in XAML bind the Children to ItemsSource. It will generate each Tab for every viewmodel we have added into the observable collection
I use a framework such as Prism, that allows you to define regions and use the
RegionManager
. You can then define aContentControl
as the 'ui' for theTabItem
Then you can use the
RegionManager.RequestNavigate
to populate a named region with a particular view (and our views import a viewmodel and set their datacontext).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
, andTab2ViewModel
. On yourMainViewModel
you keep a collection of your tab viewmodels:After setting the
DataContext
of your main window to yourMainViewModel
you can bind theDataContext
of your tabs by referencing theChildren
property: