我可以在 WPF 中使用一种具有多个 TargetType 的 Style 吗?
正如标题所示,我的意思如下:
<Style TargetType="{x:Type TextBlock}"
TargetType="{x:Type Label}"
TargetType="{x:Type Button}" >
这实际上是为了使用第3方控件,我继承了他们的类。但该模板不适用于子类,因为 TargetType
位于基类上。所以我想设置多个 TargetType
使其能够同时适用于两者。
As titled, and I mean something like below:
<Style TargetType="{x:Type TextBlock}"
TargetType="{x:Type Label}"
TargetType="{x:Type Button}" >
This is actually for the sake of using a 3rd party control, I have inherited their class. But the template doesn't apply to the SubClass because the TargetType
is on the base class. So I would like to set multiple TargetType
s to make it able to apply for both.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,你不能,但是我经常为共享基类(例如
FrameworkElement
)创建样式,然后创建基于BasedOn
基本样式的个人控件样式No you cannot, however I often create a style for a shared base class such as
FrameworkElement
, and then create my individual control styles that areBasedOn
the base styleRachel 的答案的一个更灵活的变体是对 BasedOn 使用资源密钥。
所以,而不是:
做一些类似的事情:
这提供了更多选项,因为某些样式可以基于 commonStyle,而有些样式可以基于 commonStyle2,其中 commonStyle 和 commonStyle2 都将 FrameworkElement 作为目标类型。
A more flexible variation of Rachel's answer is to use resourceKey for BasedOn.
So, instead of:
Do something like:
This gives more options as some styles can be based on commonStyle, and some on e.g. commonStyle2, where both commonStyle and commonStyle2 have FrameworkElement as target type.
答案是否定的。
TargetType
是 Style 的一个属性,只能设置一次。为了确保类型安全,样式应该针对特定类型,以便知道要设置哪些属性。不过,有一个解决方法。您可以采用所有类型的共同属性并以一种样式定义它们。然后为每个特定控件制定特定样式并使用
BaseOn
属性继承自基本样式。The answer is no.
TargetType
is a property of Style and can only be set once. To insure type safty, the style should target a specific type in order to know what properties to set.However, there is a work around. You can take the common properties of all the types you have and define them in one style. Then make specific styles for each of the specific controls and use the
BasedOn
property to inherit from the basic style.根据 Rachel 的回答,为了使代码更清晰,您可以删除标记扩展中的 x:Type 并仅使用 Type:
与以下内容相同:
Based on Rachel's answer, for cleaner code, you can remove the x:Type within the Markup Extension and just use the Type:
Is the same as:
实际上我发现在网格中你只能设置一项的样式。但是,在堆栈面板中您可以设置多个项目的样式。
请参阅以下代码:
如果您要删除它下面的位置并更改为,您将看到对象未设置,仅更改了最后一个对象的属性。
希望这有帮助。
Actually I found out that in a grid you can only set the style of one item. However, in a stackpanel you can set the style of multiple items.
See this code:
If you were to remove the place it below the and change to you will see that the objects aren't set, only the last object's properties is changed.
Hope this helps.