WPF:将多个视图绑定到TabControl的项目

问题描述:

在我们当前正在进行的项目中,我们有一个带有多个视图的主窗口(每个视图都有自己的viewmodel),这些视图在选项卡控件中显示为项目。例如:一个选项卡项是一个编​​辑器,并包含如下的编辑器视图:

In the current project we work on, we have a main window with several views (each with its own viewmodel) that are presented as items in a tab control. E.g: One tab item is an editor, and contains the editor view as follows:

<TabItem Header="Test Editor">
            <TestEditor:TestEditorView DataContext="{Binding TestEditorViewModel}"/>
</TabItem>

另一个显示结果:

<TabItem Header="Results Viewer">
     <ResultViewer:ResultViewer x:Name="resultViewer1" DataContext="{Binding Path=ResultViewModel}"  />
</TabItem>

等。

我想将TabItem绑定到主窗口的viewmodel,但是我不知道如何在不破坏MVVM模式的情况下将视图的名称绑定到任何属性。我想输入以下内容:

etc.
I'd like to have the TabItems bound to something in the main window's viewmodel, but I can't figure out how to bind the view's name to any property without breaking the MVVM pattern. I'd like to have something like:

 <TabControl.ContentTemplate>
     <DataTemplate>
         <TestEditor:TestEditorView DataContext ="{Binding TabDataContext}"/>
     </DataTemplate>
 </TabControl.ContentTemplate>

仅带有一些绑定,而不必在设计时知道将哪种类型用作内容。 br>
有什么想法吗?

only with some binding instead of having to know at design time what type will be used as content.
Any ideas?

通常,我将TabControl的标签存储在 ViewModel中,以及 SelectedIndex ,然后我使用 DataTemplates 确定哪个查看以显示

Usually I have the TabControl's Tabs stored in the ViewModel, along with the SelectedIndex, then I use DataTemplates to determine which View to display

查看:

<Window>
    <Window.Resources>
        <DataTemplate DataType="{x:Type ResultViewModel}">
            <ResultViewer:ResultViewer />
        </DataTemplate>
        <DataTemplate DataType="{x:Type EditorViewModel}">
            <TestEditor:TestEditorView />
        </DataTemplate>
    </Window.Resources>

    <TabControl ItemsSource="{Binding TabCollection}"
                SelectedIndex="{Binding SelectedTabIndex}" />

</Window>

ViewModel:

ViewModel:

public class MyViewModel : ViewModelBase
{

    publicMyViewModel()
    {
        TabCollection.Add(new ResultsViewModel());
        TabCollection.Add(new EditorViewModel());
        SelectedTabIndex = 0;
    }

    private ObservableCollection<ViewModelBase> _tabCollection
        = new ObservableCollection<ViewModelBase>();

    public ObservableCollection<ViewModelBase> TabCollection
    {
        get { return _tabCollection };
    }

    private int _selectedTabIndex;
    public int SelectedTabIndex
    {
        get { return _selectedTabIndex; }
        set
        {
            if (value != _selectedTabIndex)
            {
                _selectedTabIndex = value;
                RaisePropertyChanged("SelectedTabIndex");
            }
        }
    }
}