gpt4 book ai didi

wpf - 将样式的 TargetType 属性设置为基类

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:16 24 4
gpt4 key购买 nike

我只是在 WPF 中闲逛了一下,希望我的 Window 上的所有元素共享相同的边距。我发现所有能够有边距的控件都来自 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/27602741/

24 4 0