WPF自定义派生控件样式

Zim*_*Zim 9 c# wpf controls styles

我有一个从Button派生的自定义控件:

    class MyControl : Button{}
Run Code Online (Sandbox Code Playgroud)

并且假设这个类是空的(没有成员).

在应用程序的主窗口资源中,我使用包含大多数WPF控件样式的ResourceDictionary (所谓的主题):

    <ResourceDictionary Source="BureauBlue.xaml" />
Run Code Online (Sandbox Code Playgroud)

因此,窗口上的所有控件看起来都像是在该主题文件中定义的.但是MyControl控件上的样式不受影响.如何将MyControl看作与Button控件相同?

更新:BureauBlue.xaml中Button的样式没有键,并按以下方式定义:

    <Style TargetType="{x:Type Button}" BasedOn="{x:Null}"> ...</Style>
Run Code Online (Sandbox Code Playgroud)

Abe*_*cht 18

您在静态构造函数中覆盖DefaultStyleKey的元数据:

static MyControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(
        typeof(MyControl),
        new FrameworkPropertyMetadata(typeof(MyControl)));
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的资源中,您可以将其样式基于按钮:

<Style TargetType="{x:Type lcl:MyControl}" BasedOn="{StaticResource {x:Type Button}}" />
Run Code Online (Sandbox Code Playgroud)

我过去曾尝试覆盖DefaultStyleKey的元数据以指向基类(在您的情况下为Button),但它似乎不起作用.

  • 谢谢,这是有效的,但很奇怪:如果我在Themes/Generic.xaml中定义这样的风格,这没有任何效果.如果我在我的Window或App资源中定义这种样式,那么一切都很好.因此,当我在一个程序集中创建ButtonEx控件并将从另一个程序集中使用它时,我不清楚这种情况,那么我怎么能在我的控件库中定义我的ButtonEx控件默认情况下应该看起来像Button? (6认同)