C# 当另一个用户控件中发生事件时,如何更新用户控件?
在我的窗口中,我有树视图和文本块。树视图绑定到视图模型。树节点绑定到另一个视图模型。树视图模型提供顶级树节点的列表,树节点的视图模型提供节点子节点的列表。“我的视图模型”中的树中没有当前选定节点的概念 在文本块中,我希望显示当前选定树节点的视图模型的已知特性的值 我的问题是如何以正确的MVVM方式实现这一点?我更喜欢用XAML来做。我是否应该将该属性添加到当前选定节点的树视图模型中,然后将文本块绑定到此属性?如果是这样,我将如何向树视图模型传达树视图已更改其当前节点的事实 或者我能做得与众不同吗?我不知道怎么C# 当另一个用户控件中发生事件时,如何更新用户控件?,c#,.net,wpf,mvvm,C#,.net,Wpf,Mvvm,在我的窗口中,我有树视图和文本块。树视图绑定到视图模型。树节点绑定到另一个视图模型。树视图模型提供顶级树节点的列表,树节点的视图模型提供节点子节点的列表。“我的视图模型”中的树中没有当前选定节点的概念 在文本块中,我希望显示当前选定树节点的视图模型的已知特性的值 我的问题是如何以正确的MVVM方式实现这一点?我更喜欢用XAML来做。我是否应该将该属性添加到当前选定节点的树视图模型中,然后将文本块绑定到此属性?如果是这样,我将如何向树视图模型传达树视图已更改其当前节点的事实 或者我能做得与众不同吗
编辑:让我重新表述这个问题:当视图模型的IsSelected属性变为true时,如何将文本块内的文本设置为与所选项目相对应的视图模型的Name属性?您可以使用MVVM Light Messaging,这使得在视图模型之间以解耦的方式进行通信变得轻而易举 这里有一个很好的例子:
MVVM Light Toolkit可在此处下载:只需绑定到
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>