Managing Various DataContext in WPF
How can I deploy multiple DataContext in different tabs and controls which is the current DataContext

I am using Mvvm Light WPF4 . I have different ViewModels, but I donβt know how to handle multiple DataContext data and manage the current DataContext to change the tab switcher.
Edit:
I have a solution approach as follows:
- Create ViewModel for MainView
- The tabcontrol source is an ObservableCollection
- Each TabItem has its own DataContext.
- The menu has DataContext:
DataContext="{Binding Path=CurrentTab.DataContext}"where CurrentTab changes when a new TabItem is added to the ViewModel
I have the following issues:
- How to connect ViewModel from TabControl when changing tabs?
: , Mvvm Light ViewModelLocator ViewModel , , #, ViewModelLocator , ViewModel :
public RelayCommand MyCommand { get; set; }
private void RegisterCommand()
{
MyCommand = new RelayCommand(() =>
{
AddTab("Tab Header", new TabViewModel(), new TabContentControl());
});
}
private void AddTab(string header, object context, ContentControl content)
{
TabItem = null;
foreach(TabItem tab in TabItemList)
{
if(tab.Header.Equals(header);
{
tabItem = tab;
}
}
if(null == tabItem)
{
tabItem = new TabItem();
tabItem.Header = header;
tabItem.Content = content;
tabItem.DataContext = context;
TabItemList.Add(tabItem);
}
CurrentTabIndex = TabItemList.IndexOf(tabItem);
}
2. DataContext , ?
: :
ChangeTabCommand = new RelayCommand<TabItem>(tab =>
{
if (null == tab) return;
CurrentTabContext = tab.DataContext;
}
MainWindow.xml:
<Button Content="NewTab" Command="{Binding Path=MyCommand }" />
<TabControl
Margin="5 5 5 0"
Grid.Row="1"
ItemsSource="{Binding Path=TabItemList}"
SelectedIndex="{Binding Path=CurrentTabItemIndex}"
x:Name="Workspace">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand
Command="{Binding ChangeTabCommand }"
CommandParameter="{Binding SelectedItem, ElementName=Workspace}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TabControl>
2:
- ViewModel (ContenControl, Header, Context)