我只是在 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/
在 WPF 中,您可以设置 TargetType到类型的名称,或者您可以将其设置为 {x:Type nameOfType} . 有谁知道有什么区别? 最佳答案 没有。由于属性类型是 Type ,XAM
有什么区别 TargetType="{x:Type Button}" 和 TargetType="Button" 最佳答案 XAML 设计器应用内置类型转换器,将字符串值“Button”转换为 Sys
我为Button的TargetType定义了一个简单的buttonStyle;但将样式设置为按钮会产生异常(exception)。
我在 WPF 中创建了这个用户控件 当我编译这个时,我收到以下错误。 “UserControl1” ControlTemplate Tar
以下 TargetType 规范之间有什么区别? 1.