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

时间:2018-04-03 13:21:54

标签: wpf xaml resourcedictionary skin skinning

我想让我的自定义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>

但是没有一个资源字典被应用。你知道为什么吗?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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>