Search code examples
c#wpftreeviewtreeviewitem

Different "IsSelected" color for each node on TreeView


I have a TreeView that presents several different datatypes in a hierarchy. I have multiple HierarchicalDataTemplates defined in my UserControl.Resources, which I use to alter the look of each node depending on its datatype:

<UserControl.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:MyFirstType}" ItemsSource="{Binding Children}">
        ....
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type local:MySecondType}" ItemsSource="{Binding Children}">
        ....
    </HierarchicalDataTemplate>

    .... etc ....

</UserControl.Resources>

I'd like to have each type of node have a different hover and selected color. However, all of the examples I've found on changing these colors (for example, this question) involve changing a few system-defined resources, like HighlightBrushKey. Since I don't have access to the TreeViewItems being generated by my TreeView, how do I go about overriding these resource values on a per-item basis?


Solution

  • I accomplish that by setting the SystemColors that you mentioned to make the SelectedItem Background Transparent and then declaring my items in Border elements so that I can set their Background colours individually using a DataTrigger and a RelativeSource Binding:

    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
    <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
    

    ...

    <HierarchicalDataTemplate DataType="{x:Type local:MyFirstType}" 
        ItemsSource="{Binding Children}">
        <Border>
            <Border.Style>
                <Style TargetType="{x:Type Border}">
                    <Setter Property="Background" Value="AliceBlue" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsSelected, RelativeSource={
                            RelativeSource AncestorType={x:Type TreeViewItem}}}" 
                            Value="True">
                            <Setter Property="Background" Value="LightGreen" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
        </Border>
        <!-- Your content here -->
    </HierarchicalDataTemplate>