让我们从模型的角度来检查一下:
假设我们有 2 种不同类型的视图,1 种视图模型:
ViewA --> 使用 DataTempate/DataTemplateSelector 在项目控件中创建,绑定 > 到 ViewModelA
ViewB --> 使用 DataTempate/DataTemplateSelector 在项目控件中创建,绑定到 ViewModelA
如果两个视图都绑定到同一个视图模型,您最终会得到相同的视图。
让我们用 2 种不同类型的视图和 2 种不同类型的视图模型再试一次:
ViewA --> 使用 DataTempate/DataTemplateSelector 在项控件中创建,绑定到 ViewModelA --> 绑定到 ModelA
ViewB --> 使用 DataTempate/DataTemplateSelector 在项目控件中创建,绑定到 ViewModelB --> 绑定到 ModelB
这是可能的。
现在,如果您像这样(伪代码)对视图模型和模型进行建模:
public PhoneBookViewModel
{
public PhoneBookViewModel()
{
_parties = new ObservalbeCollection<PartyViewModel>();
}
private PhoneBook _dataContext;
// This is the property the VM uses to access the model
public PhoneBook DataContext
{
get { return _dataContext; }
set
{
if (_dataContext != null)
{
_dataContext.Parties.CollectionChanged -= OnModelPartiesChanged;
}
_dataContext = value;
if (_dataContext != null)
{
_dataContext.Parties.CollectionChanged += OnModelPartiesChanged;
}
}
}
private ObservableCollection<PartyViewModel> _parties;
// This is the property the view uses to access the collection of VM parties
public ObservableCollection<PartyViewModel> PartiesViewModels { get { return _parties; } }
private void OnModelPartiesChanged(...)
{
// Add/remove VMs to/from PartiesViewModels here
}
}
// Model
public PhoneBook
{
public PhoneBook()
{
_parties = new ObservalbeCollection<Party>();
}
private ObservableCollection<Party> _parties;
// This is the property the VM uses to access the model's parties
public ObservableCollection<Party> Parties { get { return _parties; } }
}
public PersonViewModel : PartyViewModel
{
new Person DataContext { get; set; }
}
public PartyViewModel
{
public Party DataContext { get; set; }
}
那么您将获得每个模型项的正确类型的虚拟机,
视图将绑定到 VM 项,而不是模型项。
视图的数据模板:
<DataTemplate x:Target={x:Type myVmNamespace:PersonViewModel}">
<PersonView/>
</DataTemplate>
<DataTemplate x:Target={x:Type myVmNamespace:GroupViewModel}">
<GroupView/>
</DataTemplate>
视图的项目控件:
<!-- Bind to Parties property of PhoneBookVM -->
<!-- Uses datatemplates for items -->
<ListView ItemsSource={Binding Parties}"/>