0

I am trying to build a TreeView in wpf. I need my parent and child to be in different colors, and I need that to be done for all the parents in that TreeView. If any node contains any child node, that colors also need to be changed.

enter image description here

I need that AMPHIBIANS and SPIDERS in same background color and all the child items should contains another background color. How to do this...?

So far i have tried

<Window.Resources>
    <Style TargetType="{x:Type TreeViewItem}">
        <Setter Property="Background" Value="#4E4E4E"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="15"/>
    </Style>

    <Style x:Key="styTvMenu" TargetType="{x:Type TreeView}">
        <Setter Property="Foreground" Value="Green"/>
    </Style>
</Window.Resources>
<Grid>
    <TreeView ItemsSource="{x:Static local:MainWindow.AnimalCategories}"  Style="{StaticResource styTvMenu}" Margin="0,0,321,0">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=Animals}">
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Name}"/>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
                <TextBlock  Text="{Binding Path=Category}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>

    </TreeView>
</Grid>
ASh
  • 34,632
  • 9
  • 60
  • 82
Dah Sra
  • 4,107
  • 3
  • 30
  • 69

1 Answers1

2

if TreeViewItem should have one color when it has child items and another color without them, it is possible to set a trigger like this

<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="Background" Value="#4E4E4E"/>
    <Style.Triggers>
        <Trigger Property="HasItems" Value="False">
            <Setter Property="Background" Value="Aqua"/>
        </Trigger>
    </Style.Triggers>
</Style>

another way would be wrapping TextBlocks into Border with Background. Here Background can be set for each type individually.

<DataTemplate>
     <Border Background="Aqua" Margin="4">
          <TextBlock Text="{Binding Path=Name}"/>
     </Border>
</DataTemplate>

I set Margin="4" for Border to enable default highlight of selected items

ASh
  • 34,632
  • 9
  • 60
  • 82
  • is there any way to show that color for the entire row..? Now it only fills around the text.I need it to fill the entire row ( treeview ) width – Dah Sra Apr 08 '16 at 14:10
  • 1
    @dahsra, http://stackoverflow.com/questions/15826637/wpf-treeview-item-background-over-entire-row and its linked questions – ASh Apr 08 '16 at 14:15