Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent children of a TreeView's selected item from inheriting its formatting?

I have a treeview in which i need to set the font of only selected node as bold.. It works fine if the node does not have any children. But in case a node having children is selected, the child nodes are also shown as bold..

Using following XAML:

<TreeView.ItemContainerStyle>
 <Style TargetType="TreeViewItem">
  <Style.Triggers>
   <Trigger Property="IsSelected" Value="True">
    <Setter Property="FontWeight" Value="Bold"></Setter>
   </Trigger>
  </Style.Triggers>
 </Style>
</TreeView.ItemContainerStyle>
like image 277
Arihant Avatar asked Oct 29 '11 23:10

Arihant


1 Answers

Edit: You can just use a setter to prevent the inheritance:

 <Style TargetType="TreeViewItem">
  <!-- This has precedence over inheritance -->
  <Setter Property="FontWeight" Value="Normal"/>
  <Style.Triggers>
   <Trigger Property="IsSelected" Value="True">
    <Setter Property="FontWeight" Value="Bold"></Setter>
   </Trigger>
  </Style.Triggers>
 </Style>

Or you could move this logic into the data-template, so it is not inherited down, e.g.

<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Items}">
        <TextBlock Text="{Binding Name}">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=TreeViewItem}}"
                                    Value="True">
                                    <Setter Property="FontWeight" Value="Bold"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>
like image 101
H.B. Avatar answered Nov 15 '22 06:11

H.B.