C# 如何使用某种颜色突出显示树视图选定的项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/876759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:06:34  来源:igfitidea点击:

How do I highlight a treeview selected item with some color?

c#wpfxamltreeviewselecteditem

提问by

I have a treeview in WPF. I want a different color when i select the treeviewitem.

我在 WPF 中有一个树视图。当我选择 treeviewitem 时,我想要不同的颜色。

回答by CodingNinja

Try following code. It should work.

尝试以下代码。它应该工作。

<Style TargetType="{x:Type TreeViewItem}">
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="Yellow"/>
        </Trigger>
    </Style.Triggers>
</Style>

回答by hevgen

Simple Trigger in TreeView.ItemContainerStylecan't help for default TreeView template.

TreeView.ItemContainerStyle 中的简单触发器无法帮助默认 TreeView 模板。

For standard template highlighting is done via background changing for specific element inside TreeView template. This specific element is not accessible for programmer without TreeView template changing. By default resource is used to set background on this element for highlighting.

对于标准模板突出显示是通过特定的背景更改完成的 TreeView 模板中的元素。如果不更改 TreeView 模板,程序员将无法访问此特定元素。默认资源用于在此元素上设置背景以突出显示。

So there are few ways:

所以有几种方法:

  1. simple (but side effects possible): redefine resource with key {x:Static SystemColors.HighlightBrushKey}for TreeView or ItemsPaneltemplate;
  2. Redefine complete Template for TreeView.
  1. 简单(但可能有副作用):使用键{x:Static SystemColors.HighlightBrushKey}为 TreeView 或ItemsPanel模板重新定义资源;
  2. 重新定义 TreeView 的完整模板。