1

TreeViewで選択されているアイテムのタイプに応じて異なるDataTemplatesを使用したい

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で-typeアイテムが選択されている場合にのみ、プロパティLabelが表示されます。残念ながら、そうではありません。TreeViewで何を選択しても、何も表示されません。DescriptionDocument

TreeView自体は、既存のモデルで問題なく機能します。

4

2 に答える 2

1

DataTemplateSelectorクラスを使用して、実行時に異なるデータテンプレートを適用できます。

DataTemplateSelector

于 2012-07-12T09:38:32.790 に答える
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>

上記のコードは魅力のように機能します

于 2012-07-12T10:09:35.730 に答える