gpt4 book ai didi

c# - 当另一个用户控件中发生事件时如何更新用户控件?

转载 作者:行者123 更新时间:2023-12-03 10:30:41 26 4
gpt4 key购买 nike

在我的窗口中,我有 TreeView 和一个文本 block 。 TreeView 绑定(bind)到 View 模型。树节点绑定(bind)到另一个 View 模型。 TreeView 模型提供顶级树节点的列表,树节点的 View 模型提供节点子节点的列表。在我的 View 模型中,树中没有当前选定节点的概念。

在文本 block 中,我想显示当前选定树节点的 View 模型的已知属性的值。

我的问题是这是如何以正确的 MVVM 方式完成的?我宁愿用 XAML 来做。我应该将属性添加到当前选定节点的 TreeView 模型中,然后简单地将文本 block 绑定(bind)到该属性吗?如果是这样,我将如何向 TreeView 模型传达 TreeView 已更改其当前节点的事实?

或者我可以做不同的吗?我不知道怎么...

编辑:让我重新表述一下问题:当 View 模型的 IsSelected 属性变为 true 时,如何将文本 block 内的文本设置为与所选项目对应的 View 模型的 Name 属性?

最佳答案

只需绑定(bind)到 SelectedItemTreeView元素本身。

这是一个使用 XmlDataProvider 的非常简单的示例。 . DataTemplateContentPresenter是魔法发生的地方:

<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>

关于c# - 当另一个用户控件中发生事件时如何更新用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3788308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com