问题
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;
}
来源:https://stackoverflow.com/questions/28036479/how-to-find-the-current-active-tab-in-josh-smiths-mvvm-demo-app