2012-07-12 34 views
1

我想用不同的DataTemplates取決於一個TreeView選擇什麼類型的項目標籤的DataTemplate因所選項目

XAML

<TreeView Name="SourceDocumentsList" ItemsSource="{Binding SourceDocuments}"> 
    <TreeView.Resources> 
     <HierarchicalDataTemplate DataType="{x:Type docom:Document}" ItemsSource="{Binding Blocks}"> 
      <TextBlock Text="{Binding Filename}" /> 
     </HierarchicalDataTemplate> 
    </TreeView.Resources> 
</TreeView> 
<Label Name="DescriptionLabel" 
     DataContext="{Binding ElementName=SourceDocumentsList, Path=SelectedItem}"> 
    <Label.Resources> 
     <DataTemplate x:Key="DocumentTemplate" DataType="{x:Type docom:Document}"> 
      <TextBlock Text="{Binding Description}" /> 
     </DataTemplate> 
    </Label.Resources> 
</Label> 

在我的理解中,Label將顯示Description只有在TreeView中選擇Document-類型的項目時才屬性。不幸的是,情況並非如此。它不顯示任何內容,無論我在TreeView中選擇什麼。

TreeView本身適用於我現有的模型。

回答

1

你提供一把鑰匙,這意味着模板不能被隱式應用。

<Window x:Class="WpfApplication10.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfApplication10" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition/> 
      <RowDefinition/> 
     </Grid.RowDefinitions> 
     <TreeView ItemsSource="{Binding}" Name="lst"/> 
     <Label Grid.Row="1" Content="{Binding ElementName=lst, Path=SelectedItem}"> 
      <Label.Resources> 
       <DataTemplate DataType="{x:Type local:Class1}"> 
        <TextBox Text="{Binding Foo}"/> 
       </DataTemplate> 
      </Label.Resources> 
     </Label> 
    </Grid> 
</Window> 

上面的代碼就像一個魅力

+0

沒有密鑰 – 2012-07-12 11:10:53

+0

檢查我的編輯也不起作用... – Jaster 2012-07-12 11:36:17

1

您可以使用DataTemplateSelector類在運行時應用不同的數據模板。

DataTemplateSelector

+0

但爲什麼我需要嗎? TreeView的DataTemplate也可以在沒有選擇器的情況下工作? – 2012-07-12 09:42:39