允许从朝向所述模型的视图检查此:
让我们假设我们有2种不同类型的视图,1型视图模型的:
ViewA - >内的创建项目控件使用DataTempate/DataTemplateSelector,绑定到ViewModelA
ViewB - >使用DataTempate/DataTemplateSelector在项目控件中创建,绑定到ViewModelA
如果两个视图绑定到同一个视图模型,你最终会得到同样的观点。
允许与2种不同类型的视图和2种不同类型的视图模型的再试:
ViewA - 使用DataTempate/DataTemplateSelector,绑定到ViewModelA CONTROL>一个项目内创建 - >绑定到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项目,而不是模型项目。
查看的的DataTemplates:
<DataTemplate x:Target={x:Type myVmNamespace:PersonViewModel}">
<PersonView/>
</DataTemplate>
<DataTemplate x:Target={x:Type myVmNamespace:GroupViewModel}">
<GroupView/>
</DataTemplate>
查看的ItemsControl的:
<!-- Bind to Parties property of PhoneBookVM -->
<!-- Uses datatemplates for items -->
<ListView ItemsSource={Binding Parties}"/>
我没有详细介绍所有的管道细节(例如集合后面的只读字段,以便将OnCollectionChanged注册到正确的集合)。但是这种方法确实很好(多次使用过)。 – 2011-04-17 15:17:37
这对我来说没什么意义:-) PhoneBookViewModel中的PhoneBook DataContext是什么,它与两个PartyViewModel有什么关系?我不明白。 – 2011-04-17 17:23:26
添加了更多详细信息。基本上,虚拟机连接到M的方式与V连接到虚拟机的方式类似。 – 2011-04-17 17:39:48