根据所选项目标记DataTemplate

时间:2012-07-12 09:34:18

标签: c# wpf data-binding

我想使用不同的DataTemplates,具体取决于在TreeView中选择的项目类型

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>

据我了解,只有在TreeView中选择Label - 类型项时,Description才会显示Document属性。不幸的是,事实并非如此。无论我在TreeView中选择什么,它都不显示任何内容。

TreeView本身可以与我现有的模型一起使用。

2 个答案:

答案 0 :(得分:1)

您可以使用DataTemplateSelector类在运行时应用不同的数据模板。

DataTemplateSelector

答案 1 :(得分: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>

上面的代码就像魅力一样