WPF custom derived control style

前端 未结 5 1211
难免孤独
难免孤独 2021-01-04 22:04

I have a custom control derived from Button:

    class MyControl : Button{}

And suppose, this class is empty (has no members).

In t

相关标签:
5条回答
  • 2021-01-04 22:37

    The TargetType property doesn't work for classes that derive from the specified type. See this question

    0 讨论(0)
  • 2021-01-04 22:51

    I use SetResourceReference

    SetResourceReference(StyleProperty, typeof(Button));
    
    0 讨论(0)
  • 2021-01-04 22:52

    For doing this completely in code this answer on another forum works

    this.Style = new Style(GetType(), this.FindResource(typeof(System.Windows.Controls.Button)) as Style);
    
    0 讨论(0)
  • 2021-01-04 22:53

    Check if style for Button is there in your BureauBlue.xaml and remove x:key attribute from the style if it is there

    0 讨论(0)
  • 2021-01-04 22:57

    You override the DefaultStyleKey's metadata in your static constructor:

    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(MyControl),
            new FrameworkPropertyMetadata(typeof(MyControl)));
    }
    

    Then, in your resources, you can base its style on the button:

    <Style TargetType="{x:Type lcl:MyControl}" BasedOn="{StaticResource {x:Type Button}}" />
    

    I've tried in the past to override the DefaultStyleKey's metadata to point to the base class (Button in your case), but it doesn't seem to work.

    0 讨论(0)
提交回复
热议问题