将样式的 TargetType 属性设置为基类 [英] Setting a style's TargetType property to a base class

查看:35
本文介绍了将样式的 TargetType 属性设置为基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 WPF 中闲逛了一下,并希望我的 Window 上的所有元素共享相同的边距.我发现所有具有边距的控件都来自 FrameworkElement,因此我尝试了以下操作:

I was just poking around a bit in WPF and wanted all elements on my Window to share the same margin. I found that all Controls that are capable of having a margin derive from FrameworkElement so I tried the following:

<Window.Resources>
<Style TargetType="{x:Type FrameworkElement}">
    <Setter Property="Margin" Value="10" />
</Style>
</Window.Resources>

而且,这不起作用.我可以将此应用于所有按钮,但不能应用于所有派生自 Button 的元素.我是不是遗漏了什么,或者这根本不可能?

And, this doesn't work. I can apply this to all Buttons, but not to all Elements that derive from Button. Am I missing something or is this simply not possible?

我是不是唯一一个觉得将 CSS 用于 WPF 是个好主意的人?

Am I the only one feeling like using CSS for WPF would have been a good idea?

推荐答案

很遗憾,您无法将样式应用于基础 FrameworkElement 类型;虽然 WPF 可以让您编写样式,但它不会将其应用于派生自它的控件.看来这也适用于 FrameworkElement 的子类型,例如ButtonBase,Button/ToggleButton/RepeatButton 的超类型.

Unfortunately, you cannot apply styles to the base FrameworkElement type; while WPF will let you write the style, it will not apply it to the controls that derive from it. It appears that this also applies to subtypes of FrameworkElement, e.g. ButtonBase, the supertype of Button/ToggleButton/RepeatButton.

您仍然可以使用继承,但您必须使用显式的 BasedOn 语法将其应用到您希望它应用到的控件类型.

You can still use inheritance, but you will have to use the explicit BasedOn syntax to apply it to the control types you want it to apply to.

<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>

这篇关于将样式的 TargetType 属性设置为基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆