2010-09-24 60 views
1

我的窗口中有树形视图和文本块。树视图绑定到视图模型。树节点绑定到另一个视图模型。树视图模型提供顶级树节点的列表,并且树节点的视图模型提供节点子节点的列表。在我的视图模型中没有树中当前选定节点的概念。如何在另一个用户控件中发生事件时更新用户控件?

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

我的问题是,这是如何做到正确的MVVM方式?我宁愿在XAML中做。我应该将属性添加到当前选定节点的树视图模型,然后将文本块绑定到此属性?如果是这样,我将如何向树视图模型传达树视图已更改其当前节点的事实?

或我可以做不同?我不知道如何......

编辑:让我改述一个问题:当视图模型的IsSelected属性变为true时,如何将文本块内的文本设置为与所选项对应的视图模型的Name属性?

回答

1

只需绑定到SelectedItemTreeView元素本身。

下面是一个非常简单的例子,它使用了XmlDataProviderContentPresenter上的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 [email protected]}"/> 
    </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 [email protected]}"/> 
     </DataTemplate> 
     </ContentPresenter.ContentTemplate> 
    </ContentPresenter> 
    </DockPanel> 
</Page> 
相关问题