在我的窗口中,我有树状视图和文本块。树形视图绑定到视图模型。树节点被绑定到另一个视图模型。树视图模型提供顶级树节点的列表,树节点的视图模型提供节点子节点的列表。在我的视图模型中,树中没有当前所选节点的概念。
在文本块中,我希望显示当前所选树节点的视图模型的已知属性的值。
我的问题是,如何以正确的MVVM方式完成这项工作?我更喜欢用XAML做这件事。我是否应该将属性添加到当前所选节点的树视图模型中,然后简单地将文本块绑定到此属性?如果是这样,我该如何向树视图模型传达树视图已更改其当前节点的事实?
或者我可以用不同的方式来做呢?我不知道怎么..。
编辑:让我重新表述这个问题:当视图模型的IsSelected属性变为true时,如何将文本块中的文本设置为与所选项目对应的视图模型的Name属性?
发布于 2010-09-26 04:23:35
只需绑定到TreeView元素本身的SelectedItem即可。
这里有一个使用XmlDataProvider的非常简单的示例。ContentPresenter上的DataTemplate是魔术发生的地方:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<XmlDataProvider x:Key="Data" XPath="Tree">
<x:XData>
<Tree xmlns="" Text="Test">
<Node Text="Weapon">
<Node Text="Sword">
<Node Text="Longsword"/>
<Node Text="Falchion"/>
<Node Text="Claymore"/>
</Node>
<Node Text="Polearm">
<Node Text="Halberd"/>
<Node Text="Pike"/>
</Node>
</Node>
<Node Text="Armor">
<Node Text="Cloth Armor"/>
<Node Text="Leather Armor"/>
<Node Text="Ring Mail"/>
<Node Text="Plate Mail"/>
</Node>
<Node Text="Shield">
<Node Text="Buckler"/>
<Node Text="Tower Shield"/>
</Node>
</Tree>
</x:XData>
</XmlDataProvider>
<HierarchicalDataTemplate x:Key="NodeTemplate" ItemsSource="{Binding XPath=Node}">
<TextBlock Text="{Binding XPath=@Text}"/>
</HierarchicalDataTemplate>
</Page.Resources>
<DockPanel>
<TreeView
x:Name="Objects"
ItemsSource="{Binding Source={StaticResource Data}, XPath=Node}"
ItemTemplate="{StaticResource NodeTemplate}"/>
<ContentPresenter Content="{Binding ElementName=Objects, Path=SelectedItem}">
<ContentPresenter.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding XPath=@Text}"/>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</DockPanel>
</Page>发布于 2010-09-25 17:54:18
您可以使用MVVM Light Messaging,这使得视图模型之间的通信变得轻而易举,以一种解耦的方式。
这里有一个很好的例子:http://chriskoenig.net/2010/07/05/mvvm-light-messaging/
MVVM Light Toolkit可在此处下载:http://mvvmlight.codeplex.com/
https://stackoverflow.com/questions/3788308
复制相似问题