如何合并自定义 TreeViewItem 样式和皮肤?

How to merge custom TreeViewItem style and skin?

我想让我的自定义 TreeViewItem 样式可换肤。我试图按照有关此事的教程进行操作,但是我在从简单案例抽象到多个文件中的多个资源字典的案例时遇到了问题。

我在文件中为我的 TreeViewItem 定义了自定义样式:

<ResourceDictionary  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="*****namespace omitted******">

    <Style x:Key="GroupedTreeViewItemStyle" TargetType="{x:Type TreeViewItem}">

        <!-- Most of the content omitted, see below as an example of skin reference -->

        <ControlTemplate TargetType="{x:Type TreeViewItem}">
            <ControlTemplate.Triggers>
                <Trigger Property="IsSelected" Value="true">
                    <Setter Property="Background" TargetName="Bd" Value="{DynamicResource BackgroundHighlightBrush}"/>
                    <Setter Property="Foreground" Value="{DynamicResource TextHighlightBrush}"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Style>
</ResourceDictionary>

然后我们有了默认皮肤,定义了我们需要的两个画笔:

<ResourceDictionary  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="*****namespace omitted*****">

    <!-- Text Color brushes -->
    <SolidColorBrush x:Key="TextHighlightBrush" Color="White"/>


    <!-- Box Color Brushes -->
    <SolidColorBrush x:Key="BackgroundHighlightBrush" Color="Black"/>

</ResourceDictionary>

最后我尝试将两个资源字典添加到树视图项目资源中,如下所示:

<TreeView Name="treeView" ItemsSource="{Binding}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <TreeView.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary>
                    <Style TargetType="TreeViewItem">
                        <Setter Property="IsExpanded"  Value="{Binding Expanded, Mode=TwoWay}"/>
                    </Style>
                </ResourceDictionary>
                <ResourceDictionary  Source="../../Skins/Default.xaml"/>
                <ResourceDictionary  Source="GroupedTreeViewItemStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </TreeView.Resources>
</TreeView>

但是 none 的资源字典被应用。你知道为什么吗?

在此先感谢您的帮助!

GroupedTreeViewItemStyle 存在但未在任何地方应用。您可以使用 BasedOn 属性:

从该样式派生默认的 TreeViewItem 样式
<TreeView.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary  Source="../../Skins/Default.xaml"/>
            <ResourceDictionary  Source="GroupedTreeViewItemStyle.xaml"/>
        </ResourceDictionary.MergedDictionaries>

        <Style TargetType="TreeViewItem" BasedOn="{StaticResource GroupedTreeViewItemStyle}">
            <Setter Property="IsExpanded"  Value="{Binding Expanded, Mode=TwoWay}"/>
        </Style>
    </ResourceDictionary>
</TreeView.Resources>