如何使 WPF 样式可继承到派生类? [英] How to make a WPF style inheritable to derived classes?

查看:33
本文介绍了如何使 WPF 样式可继承到派生类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的 WPF 应用程序中,我们有一个带有 TargetType={x:Type ContextMenu} 的全局样式.我创建了一个派生自 ContextMenu 的 MyContextMenu,但现在默认样式不适用.

In our WPF app we have a global style with TargetType={x:Type ContextMenu}. I have created a MyContextMenu that derives from ContextMenu, but now the default style does not apply.

如何告诉 WPF 我希望 MyContextMenu 继承 ContextMenu 的默认样式?希望我可以在我的控件本身中做到这一点(通过静态 ctor 元数据覆盖或其他什么?),而不必在任何 xaml 中乱七八糟.

How can I tell WPF that I want MyContextMenu to inherit the default style from ContextMenu? Hopefully I can do this from within my control itself (via static ctor metadata override or something?) and not have to mess around in any xaml.

推荐答案

如果您在应用程序中定义了一个样式,如下所示:

If you have a Style defined in your application like so:

<Style TargetType="{x:Type ContextMenu}" ...

那是隐式样式,而不是默认样式.默认样式通常位于与控件相同的程序集中或匹配的程序集中(即 MyAssembly.Aero.dll).

Then that is an implicit Style, not a default Style. Default Styles are generally located in the same assembly as the control or in matching assemblies (i.e. MyAssembly.Aero.dll).

隐式样式不会自动应用于派生类型,这可能是您所看到的.

Implicit Styles are not automatically applied to derived types, which is probably what you are seeing.

您可以定义第二个样式,如下所示:

You can either define a second Style, like so:

<Style x:Key="{x:Type ContextMenu}" TargetType="{x:Type ContextMenu}" ...
<Style TargetType="{x:Type local:MyContextMenu}" BasedOn="{StaticResource {x:Type ContextMenu}}" ...

或者您可以利用控件的 Style 属性.您可以从 XAML 执行以下操作

Or you can leverage the Style property of your control. You could do the following from XAML

<local:MyContextMenu Style="{DynamicResource {x:Type ContextMenu}}" ...

或者你可以在你的 MyContextMenu 中这样做:

or you can do this in your MyContextMenu like so:

public MyContextMenu() {
    this.SetResourceReference(StyleProperty, typeof(ContextMenu));
}

这篇关于如何使 WPF 样式可继承到派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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