扩展自定义TreeView项目容器样式?

时间:2013-02-25 22:00:29

标签: wpf styles itemcontainerstyle basedon

如何扩展我在CustomTreeView中声明的样式?这样我有一个浅灰色的前景和一个绿色背景?

CustomTreeView.xaml

<TreeView x:Class="WpfApplication17.CustomTreeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="Foreground" Value="LightGray"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

Window.xaml

<Window x:Class="WpfApplication17.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication17">
    <local:CustomTreeView ItemsSource="{Binding Data}">
        <local:CustomTreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource {x:Type TreeViewItem}}">
                <Setter Property="Background" Value="Green"/>
            </Style>
        </local:CustomTreeView.ItemContainerStyle>
    </local:CustomTreeView>
</Window>

1 个答案:

答案 0 :(得分:0)

不确定这是否是正确的方法,但我最终使用它。

<TreeView x:Class="WpfApplication17.CustomTreeView"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <TreeView.Resources>
            <Style x:Key="m_itemContainerStyle" TargetType="{x:Type TreeViewItem}">
                <Setter Property="Foreground" Value="LightGray"/>
            </Style>
        </TreeView.Resources>

        <TreeView.ItemContainerStyle>
            <Style BasedOn="{StaticResource m_itemContainerStyle}" TargetType="{x:Type TreeViewItem}">

            </Style>
        </TreeView.ItemContainerStyle>
    </TreeView>


    <Window x:Class="WpfApplication17.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication17">
        <local:CustomTreeView ItemsSource="{Binding Data}">
            <local:CustomTreeView.ItemContainerStyle>
                <Style BasedOn="{StaticResource m_itemContainerStyle}"  TargetType="{x:Type TreeViewItem}">
                    <Setter Property="Background" Value="Green"/>
                </Style>
            </local:CustomTreeView.ItemContainerStyle>
        </local:CustomTreeView>
    </Window>