让我们从模型的角度来检查这一点:
假设我们有 2 种不同类型的视图,1 种类型的视图模型:
ViewA --> 使用 DataTemplate/DataTemplateSelector 在 itemscontrol 内创建,绑定 > 到 ViewModel
ViewB --> 使用 DataTemplate/DataTemplateSelector 在 itemscontrol 中创建,绑定到 ViewModel
如果两个视图都绑定到相同的视图模型,那么您最终会得到相同的视图。
让我们用 2 种不同类型的视图和 2 种不同类型的视图模型重试:
ViewA --> 使用 DataTempate/DataTemplateSelector 在项目控件中创建,绑定到 ViewModelA --> 绑定到 ModelA
ViewB --> 使用 DataTemplate/DataTemplateSelector 在项目控件中创建,绑定到 ViewModel --> 绑定到模型 B
这个有可能。
现在,如果您像这样对视图模型和模型进行建模(伪代码):
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}"/>