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

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

问题描述

在我们的WPF应用程序,我们有 =的TargetType全局样式{X:输入文本菜单} 。我创建了从文本菜单派生的将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继承从文本菜单的默认样式?希望我能在我的控制本身内做到这一点(通过静态构造函数的元数据覆盖或东西吗?),并没有惹任何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}}" ...

或者你可以利用你的控制的样式属性。你可以做的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天全站免登陆