且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF MVVM:将不同的ViewModel绑定到每个TabItem吗?

更新时间:2021-09-14 02:28:10

您确实可以将选项卡的视图模型添加到主视图模型中.然后,您可以为选项卡绑定到XAML中的子视图模型.

You can indeed add the view models for your tabs to a main view model. You can then bind to the child view models in the XAML for your tabs.

假设您有三个视图模型:MainViewModelTab1ViewModelTab2ViewModel.在MainViewModel上,您保留了选项卡视图模型的集合:

Say that you have three viewmodels: MainViewModel, Tab1ViewModel, and Tab2ViewModel. On your MainViewModel you keep a collection of your tab viewmodels:

class MainViewModel
{
    ObservableCollection<object> _children;

    public MainViewModel()
    {
        _children = new ObservableCollection<object>();
        _children.Add(new Tab1ViewModel());
        _children.Add(new Tab2ViewModel());
    }

    public ObservableCollection<object> Children { get { return _children; } }
}

将主窗口的DataContext设置为MainViewModel之后,您可以通过引用Children属性来绑定选项卡的DataContext:

After setting the DataContext of your main window to your MainViewModel you can bind the DataContext of your tabs by referencing the Children property:

<TabControl>
    <TabItem DataContext="{Binding Children[0]}" x:Name="Tab1" Header="Tab1" >
      <!-- Tab content -->
    </TabItem>
    <TabItem DataContext="{Binding Children[1]}" x:Name="Tab2" Header="Tab2" >
      <!-- Tab content -->
    </TabItem>
</TabControl>