我只是在 WPF 中闲逛了一下,希望窗口上的所有元素共享相同的边距。 我发现所有能够具有边距的控件都源自 FrameworkElement,因此我尝试了以下操作:
<Window.Resources>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="10" />
</Style>
</Window.Resources>
而且,这行不通。 我可以将其应用于所有按钮,但不能应用于从按钮派生的所有元素。 我错过了什么还是这根本不可能?
我是唯一一个觉得在 WPF 中使用 CSS 是个好主意的人吗?
最佳答案
不幸的是,您无法将样式应用于基本 FrameworkElement 类型;虽然 WPF 允许您编写样式,但它不会将其应用于派生自它的控件。看来这也适用于 FrameworkElement 的子类型,例如ButtonBase,Button/ToggleButton/RepeatButton 的父类(super class)型。
您仍然可以使用继承,但您必须使用显式的 BasedOn
语法将其应用到您希望其应用的控件类型。
<Window.Resources>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="10" />
</Style>
<Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
</Window.Resources>
关于wpf - 将样式的 TargetType 属性设置为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1026635/