2010-09-24 34 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> 
相關問題