我能否使WPF ListBox继承父元素的画刷?

3
我的WPF窗口的前景画刷设置为来自资源字典的画刷,我希望窗口中的所有文本都具有此颜色,因此我不会在任何其他地方触摸前景画刷。
文本框获取颜色 文本块获取颜色 按钮获得颜色
列表框不获取颜色,因此它们的内容也不获取颜色。
是否有任何方法使列表框在这方面像其他控件一样工作?
假设没有,并且这是设计原则,那么这个原则的基础是什么?
编辑:
似乎我的问题不够清晰。
我知道如何创建样式和资源并将它们应用于ListBox;我想知道为什么对于某些控件,我需要这样做,而对于其他控件,我不需要这样做 - 为什么有些控件继承属性而其他控件则不继承 - 是否有任何方法使它们都以相同的方式继承。
3个回答

9
ListBox和其他一些控件没有继承Foreground属性的原因是,在默认样式中使用Setter显式覆盖了它。不幸的是,即使您将自定义样式分配给ListBox并且不包括Foreground属性Setter,它仍将回退到使用默认样式,然后尝试继承其父级的值。
确定属性值的优先顺序如下:
1. 本地值 2. 样式触发器 3. 模板触发器 4. 样式Setter 5. 主题样式触发器 6. 主题样式Setter 7. 属性值继承 8. 默认值
由于#6在控件的默认样式中已经定义,WPF不会尝试确定#7的值。

1
这是列表框项目的样式:
<Style x:Key="{x:Type ListBoxItem}" TargetType="ListBoxItem">
  <Setter Property="SnapsToDevicePixels" Value="true"/>
  <Setter Property="OverridesDefaultStyle" Value="true"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="ListBoxItem">
        <Border 
          Name="Border"
          Padding="2"
          SnapsToDevicePixels="true">
          <ContentPresenter />
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsSelected" Value="true">
            <Setter TargetName="Border" Property="Background"
                    Value="{StaticResource SelectedBackgroundBrush}"/>
          </Trigger>
          <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground"
                    Value="{StaticResource DisabledForegroundBrush}"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

现在,你需要修改这个代码,使得静态资源“DisabledForegroundBrush”指向你的资源画刷。将其添加到你的Window.Resource标签中,然后你就可以使用了。


1
你可以像这样做:
<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="root">
    <ListBox>
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBox}">
                <Style.Resources>
                    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Yellow"/>
                    <SolidColorBrush x:Key="{x:Static SystemColors.WindowTextBrushKey}" Color="Red"/>
                </Style.Resources>
            </Style>
        </ListBox.Resources>
        <ListBoxItem>Item 1</ListBoxItem>
        <ListBoxItem>Item 2</ListBoxItem>
    </ListBox>
</Page>

你可以使用绑定表达式将颜色绑定到应用程序定义的颜色资源,而不是使用Color="Red"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接