【问题标题】:How to apply a property to a control, without affecting its children如何将属性应用于控件,而不影响其子级
【发布时间】:2012-12-06 08:13:55
【问题描述】:

我有一个 TreeView,它像这样禁用了高亮显示:

<TreeView Name="tvFilters" Margin="0,10,0,10" Background="White" BorderBrush="White">
            <TreeView.Resources>
                <!-- Disables the blue highlighting when a TreeViewItem is clicked -->
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">
                    Transparent
                </SolidColorBrush> 
            </TreeView.Resources>
 </TreeView>

编辑:这是我的 TreeView 的一部分 - 请注意单击 TreeViewItem 后出现的灰色区域:

这是另一个:

【问题讨论】:

  • 我假设您必须设置TreeView 的样式,而不是为整个TreeView 的范围设置HighlightBrushKey...
  • 你能详细说明一下@Spontifixus 吗?

标签: c# .net wpf xaml mvvm


【解决方案1】:

要获得所需的行为,您需要为TreeViewItem 提供新的默认样式和模板。然后,您可以在此模板中更改突出显示项目的背景颜色,而不会影响 TreeViewItem 的所有子项的背景。

您可以在 MSDN 中找到包含模板的样式示例:TreeViewItem ControlTemplate Example

第一步:将样式导入您的应用程序

您需要为您的TreeView 提供样式和模板。因此,从网站复制 XAML 并将其粘贴到 TreeView 的资源部分:

<TreeView x:Name="tvFilters" ...>
    <TreeView.Resources>

        <!-- paste copied styles here -->

    </TreeView.Resources>
</TreeView>

注意:确保您还复制了所提供示例底部​​的名为 GlyphBrushSolidColorBrush。否则你的代码将无法工作。

第二步:修改代码以满足您的需求

要使代码按您的意愿工作,您需要进行一些修改。

  1. 从下面一行中删除x:Key="{x:Type TreeViewItem}"

    <Style x:Key="{x:Type TreeViewItem}" TargetType="{x:Type TreeViewItem}">
    

    看起来像

    <Style TargetType="{x:Type TreeViewItem}">
    

    这会将样式应用于TreeView中的所有项目

  2. TreeViewItem 的样式中找到&lt;Trigger Property="IsSelected" Value="true"&gt; 并替换

    <Setter TargetName="Bd"
            Property="Background"
            Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
    <Setter Property="Foreground" 
            Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
    

    <Setter TargetName="Bd"
            Property="Background"
            Value="Transparent" />
    <Setter Property="Foreground" 
            Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    

    注意:两个值(ForegroundBackground)都被替换了!

  3. TreeViewItem 的样式中找到具有&lt;Condition Property="IsSelected" Value="true"/&gt;&lt;MultiTrigger&gt; 并替换

    <Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
    

    <Setter TargetName="Bd" Property="Background" Value="Transparent"/>                                      
    

结果

在进行修改之前,TreeView 将如下所示:

进行修改后,TreeView 上的蓝色突出显示将消失,而 ComboBox 上仍然可用:

【讨论】:

  • 非常感谢您提供非常详细的答案。它就像一个魅力! +1 :)
  • 再次嗨,实际上我注意到发生了一些奇怪的事情 - 我希望这应该很容易解决,并且源自模板。由于某种原因,单击 TreeView 中的元素后,该元素的部分背景变为灰色。我在问题中添加了一个屏幕截图来反映这一点。
  • 当我点击 TreeView 外部时,它实际上似乎发生了
  • 我无法重现该问题。您在项目中实际拥有哪些控件?
  • 您还需要调整 MultiTrigger IsSelect = true 的背景,它就在您上面提到的那个触发器的正下方,一切都会好起来的:)
猜你喜欢
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 2022-01-21
  • 2020-07-14
  • 2023-03-24
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多