Managing Various DataContext

Managing Various DataContext in WPF

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

enter image description here

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 :

// in MainModelView.cs

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 , ?

: :

// in RegisterCommands()
ChangeTabCommand = new RelayCommand<TabItem>(tab =>
{
  if (null == tab) return;
  CurrentTabContext = tab.DataContext;
}

MainWindow.xml:

  <!-- MainWindow.xaml -->

  <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:

  1. ViewModel (ContenControl, Header, Context)
+3
1

ViewModelContainer, (, MainViewModel, Tab1ViewModel, Tab2ViewModel). ViewModelContainer DataContext DataContext TabItem VM DataContext = "{Binding Tab1ViewModel}"

2.

MVVM 100%. viewmodel. , viewmodel. ( ObservableCollection INotifyPropertyChanged) , , tabItem. , View 100% XAML ItemTemplate, , .

0

All Articles