【问题标题】:WPF Styles - Please help me understand why this works the way it doesWPF Styles - 请帮助我理解为什么它会这样工作
【发布时间】:2011-06-05 07:36:03
【问题描述】:
<Style x:Key="MyStyle">
    <Setter Property="Window.Background" Value="Orange"/>
</Style>

<Button Content="Ok" Style="{StaticResource MyStyle}"/>

如果 setter 被指定为 Window.Background,为什么按钮实际上是橙色背景?

不会给 TextBlock 一个橙色背景:

<TextBlock Style="{StaticResource MyStyle}"/>

谢谢

【问题讨论】:

    标签: wpf xaml styles


    【解决方案1】:

    ButtonWindow 都没有真正定义 Background 属性,它们都继承自 Control

    所以即使你写了Window.Background,setter 实际上是通过使用Control.BackgroundProperty 字段绑定到属性的,该字段也适用于Button

    【讨论】:

    • 谢谢斯文!但是为什么 不会使 TextBlock 的背景变为橙色? TextBlock 也继承自 Control...
    • @Gustavo, TextBlock 直接继承自 FrameworkElement,而不是继承自 Control
    • 确实,TextBlock 并没有继承自 Control,而是定义了自己的 Background 属性,所以设置 TextBlock 的背景的唯一方法就是直接在 TextBlock.Background 上使用 Setter。
    【解决方案2】:

    之所以有效,是因为 Background 属性附加到 Control 类,WindowButton 都作为祖先

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多