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

标签 wpf styles targettype

我只是在 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/

相关文章:

c# - 为 WPF 动画制作 C# 库线程安全

javascript - jQuery Mobile Ajax 导航功能和 CSS 样式

c# - 没有直接链接的二级结构化数据的 WPF 绑定(bind)

c# - 在启动时选择列表中的第一个 ComboBox 项

css - Firefox 中固定位置标题周围的白色边框

.net - Target ="someType"和 Target ="{x:Type someType}"之间的性能差异

.net - 在 WPF 中为 NestedClass 声明样式 TargetType

.net - WPF 将多个控件绑定(bind)到不同的数据上下文

javascript - 创建的元素未使用当前 JS 代码设置样式