在TreeView中突出显示父项

时间:2012-07-31 10:51:43

标签: wpf

有没有办法让Treeview中的Parent节点也有一些区别,以便用户知道他们所在的父节点?它可能是突出显示单元格或更改文本,但我希望能够单击文件夹中的项目,但父节点不同,以便用户知道他们在内部点击了什么。

谢谢。

1 个答案:

答案 0 :(得分:2)

模型级别 - 在模型类中具有“父级”属性。

E.g。如果你有一个递归绑定到TreeViewMyItemClass

的类
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.
}

所以当孩子被选中时......

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...
   } 
} 

因为父母强调......

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...
  } 
} 

然后,您可以使用此IsHighlighted标记来解除树视图项的数据上下文,然后将适当的样式应用于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>

确保您对商品类中的所有商品实施INotifyPropertyChanged,否则这些效果将无效。