WPF样式 - 请帮助我理解为什么它的工作方式

时间:2022-05-01 01:40:14
<Style x:Key="MyStyle">
    <Setter Property="Window.Background" Value="Orange"/>
</Style>

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

Why does the button actually get an orange background, if the setter is specified as Window.Background?

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

This does not give the TextBlock an orange background:

这不会给TextBlock一个橙色背景:

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

Thanks

2 个解决方案

#1


5  

Neither Button nor Window actually define the Background property, they both inherit it from Control.

Button和Window都没有实际定义Background属性,它们都从Control继承它。

So even though you wrote Window.Background, the setter is actually bound to the property by using the Control.BackgroundProperty field which also applied to Button.

因此,即使您编写了Window.Background,也可以使用同样应用于Button的Control.BackgroundProperty字段将setter绑定到该属性。

#2


2  

It works because the Background property is attached to Control class which both Window and Button have as ancestor

它的工作原理是因为Background属性附加到Control类,Window和Button都具有它作为祖先

#1


5  

Neither Button nor Window actually define the Background property, they both inherit it from Control.

Button和Window都没有实际定义Background属性,它们都从Control继承它。

So even though you wrote Window.Background, the setter is actually bound to the property by using the Control.BackgroundProperty field which also applied to Button.

因此,即使您编写了Window.Background,也可以使用同样应用于Button的Control.BackgroundProperty字段将setter绑定到该属性。

#2


2  

It works because the Background property is attached to Control class which both Window and Button have as ancestor

它的工作原理是因为Background属性附加到Control类,Window和Button都具有它作为祖先