WPF MVVM:将不同的ViewModel绑定到每个TabItem吗? [英] WPF MVVM: Binding a different ViewModel to each TabItem?
问题描述
我有一个带有选项卡控件的主窗口,其中包含2个tabItem
s:
I have a main window with a tab control containing 2 tabItem
s:
我目前有1个ViewModel
服务于Tab1& Tab2.该ViewModel
的SOC模糊化变得有点肿.我想将逻辑分为2个视图模型:ViewModel 1& ViewModel2.我的理解是,您可以将主窗口DataContext
设置为一个基本ViewModel,其中包含ViewModels&那么您可以将每个TabItem声明为不同的ViewModel.
I currently have 1 ViewModel
which services Tab1 & Tab2. This ViewModel
is becoming a little bloated with blurred SOC. I want to split the logic into 2 viewmodels: ViewModel 1 & ViewModel2. My understanding is that you can set the Main Window DataContext
to a Base ViewModel which holds a collection of ViewModels & then you can assert each TabItem to a different ViewModel.
我已经看到了这些基本ViewModel的示例,它公开了一个ObservableCOllection,如下所示:
The example's I've seen of these base ViewModels expose an ObservableCOllection like so:
private ObservableCollection<ViewModel1> _viewModelCollection
Public Observable Collection<ViewModel1> ViewModelCollection
{
get { return _viewModelCollection; }
set
{
_viewModelCollection = value;
OnPropertyChanged("ViewModelCollection");
}
}
public BaseViewModel()
{
ViewModelCollection = new ObservableCollection<ViewModel1>();
ViewModelCollection.Add(new ViewModel1(Tab1);
ViewModelCollection.Add(new ViewModel1(Tab2);
}
但是如何为每个TabItem分配一个不同的ViewModel?我想要Tab1 = ViewModel1& Tab2 = ViewModel2?
But how do I assign a different ViewModel to each TabItem? I would want Tab1= ViewModel1 & Tab2=ViewModel2?
推荐答案
您确实可以将选项卡的视图模型添加到主视图模型中.然后,您可以为选项卡绑定到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.
假设您有三个视图模型:MainViewModel
,Tab1ViewModel
和Tab2ViewModel
.在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>
这篇关于WPF MVVM:将不同的ViewModel绑定到每个TabItem吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!