【问题标题】:How to avoid childrens of groupbox taking there default styles which are defined in resource or resourcedictionary in wpf如何避免 groupbox 的子项采用 wpf 的资源或资源字典中定义的默认样式
【发布时间】:2017-11-04 19:43:21
【问题描述】:

资源中定义的样式

        <Setter Property="Background" Value="Red"/>

    </Style>enter code here
</Window.Resources>

在窗口中,我正在添加一个带有子标签的组框。

<Grid>
    <GroupBox Header="Header">
        <GroupBox.Resources>

                <Style TargetType="{x:Type GroupBox}">
                <Setter Property="Background" Value="white"/>
            </Style>
        </GroupBox.Resources>
        <Label Content="dsfdsfdsf" Foreground="Black"  />
    </GroupBox>
</Grid>

我的预期结果是标签以白色为背景。但实际上它采用的是红色背景(以 Resource 的样式定义)

如果我将 Label 的样式设置为显式 null 它工作正常

Label Content="dsfdsfdsf" Foreground="Black" Style={x:Null}

但是 GroupBox 的控件是动态添加的,所以我想将
Style={x:Null} 设置为正在添加到组框的所有子项

如果我在 Label 中将 OverrideDefalutStyle 设置为 True,则 label 的内容不会出现 ....................................

Label Content="dsfdsfdsf" Foreground="Black" OverridesDefaultStyle="True"

【问题讨论】:

  • WPF 设计中的一个痛点是我们无法像使用 CSS3 那样对元素进行样式设置。在这种情况下,Style 可以只定位 exactly 一个类型,即使派生的 Types 也不能继承该样式(例如:一个 Style 定位 Control 将无法应用来自 Control 的元素)。因此,对于您的场景,除非您事先知道动态添加元素的所有类型,否则仅使用纯 XAML(没有任何自定义附加属性或使用后面的代码破解)将不会有很好的解决方案。

标签: c# .net wpf


【解决方案1】:

GroupBox.Resources 中的样式对 GroupBox 本身没有影响。隐式 GroupBox 的样式是它在 VisualTree 上最接近的祖先之一。你把那种风格放错地方了。

或者使用 Style 属性来代替

<Grid>
    <GroupBox Header="Header">
        <GroupBox.Style>

                <Style TargetType="{x:Type GroupBox}">
                <Setter Property="Background" Value="white"/>
            </Style>
        </GroupBox.Style>
        <Label Content="dsfdsfdsf" Foreground="Black"  />
    </GroupBox>
</Grid>

【讨论】:

    【解决方案2】:

    通过设置

    <Style TargetType="{x:Type GroupBox}">
        <Setter Property="Background" Value="White"/>
    </Style>
    

    您会将 GroupBox 中所有 GroupBox 控件的背景设置为白色,并将 GroupBox 本身设置为白色。

    因此,如果您想设置/覆盖 GroupBox 中所有标签的背景,只需向您的 GroupBox 中添加一个额外的样式,目标为Label

    <Style TargetType="{x:Type Label}">
        <Setter Property="Background" Value="White"/>
    </Style>
    

    如果您想重置 Label 的样式属性,只需将空样式定义添加到您的 GroupBox

    <Style TargetType="{x:Type Label}"/>
    

    下一个方法用于你的风险:)

    如果你只想重置背景颜色,你可以用这个技巧/hack 来重置:

    <Style TargetType="{x:Type Label}">
        <Setter Property="Background" Value="{Binding Background.DefaultValue, RelativeSource={RelativeSource Self}}" />
        <Setter Property="Foreground" Value="Black" />
     </Style>
    

    提示:你也可以写成Background.ABC,而不是Background.DefaultValue,这里主要是绑定出错了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      相关资源
      最近更新 更多