在具有多个 DataTemplates 的树视图中,如何将样式仅应用于其中一个

In a tree view with multiple DataTemplates, how to apply a style to only one of them

我有一个显示不同类型对象的 TreeView 控件。我使用多个 DataTemplates,每种类型一个,并相应地设置它们的 DataType
代码:

<TreeView>
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Family}" ItemsSource = "Members">
            <!-- template omitted here-->
        </HierarchicalDataTemplate>
        <DataTemplate DataType = "{x:Type local:FamilyMember}">
            <!--template omitted-->
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

现在我想将样式应用到 HierarchicalDataTemplate,并且只应用到它。我必须使用样式,因为我设置了 TreeViewItem 的一些属性,在本例中是项目容器。 我试过了:

<HierarchicalDataTemplate DataType="{x:Type local:Family}" ItemsSource = "Members">
    <HierarchicalDataTemplate.ItemsContainerStyle>
        <Style TargetType = "TreeViewItem">
            <!-- some styling of the tree view item-->
        </Style>
    <\HierarchicalDataTemplate.ItemsContainerStyle>
    <!-- template omitted here-->
</HierarchicalDataTemplate>

但样式会应用于所有树项,甚至是那些呈现 FamilyMember 个对象的树项,它们不是同一模板。
我该怎么做?

您可以使用可能有助于您入门的 ItemContainerStyleSelector property to control which styles get applied to which items. I found an example usage in 。与该示例的主要区别在于您将根据对象的类型而不是对象的 属性 选择。