How to find the current/active Tab in Josh Smith&#

2019-08-19 13:44发布

问题:

I've been adapting Josh Smith's MVVM Demo app to suit my requirements.

I have been successful for most part of it. Now I want to add a feature "Print"(similar to a print feature that exsits in any application) in the file menu item for this applicaiton. Since I can open multiple tabs in this application, how will I know which tab(to be more specific which Workspace) was active when the user clicked the "Print"? The code below shows the DataTemplate where the TabControl is used in the DemoApp.

Any help/thoughts are greatly appreciated.

<DataTemplate x:Key="WorkspacesTemplate">
<TabControl 
  IsSynchronizedWithCurrentItem="True" 
  ItemsSource="{Binding}" 
  ItemTemplate="{StaticResource ClosableTabItemTemplate}"
  Margin="4"
  />

回答1:

First of all your DataContext is wrong, your DataContext should be a ViewModel, to which you bind the ItemsSource to a ObservableCollection Property. E.g.

<TabControl 
  IsSynchronizedWithCurrentItem="True" 
  ItemsSource="{Binding Tabs}" 
  SelectedItem={Binding SelectedTab}
  ItemTemplate="{StaticResource ClosableTabItemTemplate}"
  Margin="4"
  />

Where you have

public class MainViewModel 
{
    public ObservableCollection<TabViewModel> Tabs { get; set; }
    public TabViewModel SelectedTab { get; set; }
}

And in your window code behind, all you should have in the constructor is

public MainView()
{
    this.DataContext = new MainViewModel()
}

or

public MainView(MainViewModel vm)
{
    this.DataContext = vm;
}