Leah Smith
Leah Smith

Reputation: 87

Highlight Parent Item in TreeView

Is there a way to have the Parent node in a Treeview too have some differentiation so the user knows that is the parent they are under? It could be to highlight the cell or change the text but I want to be able to click on an item inside a folder but the parent node is different so the user knows what they have clicked inside of.

Thank you.

Upvotes: 0

Views: 1062

Answers (1)

Vinit Sankhe
Vinit Sankhe

Reputation: 19895

Model Level - Have "Parent" property in your model class.

E.g. if you have a class that is recursively bound to the TreeView say MyItemClass

public class MyItemClass
{
    public string MyHeader { get; set; } //Header text of each tree view item.
    public MyItemClass Parent { get; set; } //Parent MyItemClass object.
    public List<MyItemClass> Children { get; set; } //Children MyItemClass
    public bool IsSelected { get; set; } //When tree view item is clicked & selected.
    public bool IsHighlighted { get; set; } //When parent is highlighted.
}

So when child is selected ...

private bool _isSelected;
public bool IsSelected 
{
  get { retrn _isSelected; }
  set
  {
     _isSelected = value;

     //The line below highlights the parent when either of the child is selected.
     this.Parent.IsHighlighted 
         = this.Parent.Children.Where(item => item.IsSelected).Any();

     //Notify Property Changed here...
   } 
} 

So as the parent highlights...

private bool _isHighlighted;
public bool IsHighlighted
{
  get { retrn _isHighlighted; }
  set
  {
     _isHighlighted = value;

     //When a node is highlighted all its Parent nodes should be too.
     this.Parent.IsHighlighted 
         = this.Parent.Children.Where(item => item.IsHighlighted).Any();

     //Notify Property Changed here...
  } 
} 

You can then use this IsHighlighted flag from undelrying data context of the tree view item and then apply appropriate style to that TreeViewItem.

    <TreeView ItemsSource="{Binding MyItems}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Children}">
                <TextBlock Text="{Binding MyHeader}">
                    <TextBlock.Style>
                        <Style TargetType="{x:Type TextBlock}">
                             <Style.Triggers>
                                <DataTrigger Binding="{Binding IsHighlighted}"
                                             Value="True">
                                    <Setter Property="FontWeight" Value="Bold"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>
                </TextBlock>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>

Make sure that you implement INotifyPropertyChanged on all the properties in your item class otherwise these effects wont work.

Upvotes: 2

Related Questions