Reputation: 4445
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.
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>
Upvotes: 0
Views: 2809
Reputation: 35733
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
Upvotes: 3