2012-07-12 66 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