Neil Mitchell
Neil Mitchell

Reputation: 9250

Style inherited control like base control

In WPF/C# I want to define a new class inheriting from an existing control, but which uses the style of the base control. For example:

class MyComboBox : ComboBox
{
    void MyExtraMethod(){...}
}

I dynamically switch to Luna style by doing:

 var uri = new Uri("/PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\\themes/Luna.normalcolor.xaml", UriKind.Relative);
 var r = new ResourceDictionary();
 r.Source = uri;
 this.Resources = r;

While this correctly styles all instances of ComboBox with Luna themes, the MyComboBox control ends up with the Classic theme. How do I make MyComboBox inherit its style from ComboBox?

I am writing all my WPF in code, without using XAML markup. I suspect the Style and BasedOn properties are relevant, but I haven't managed to figure out exactly how.

Upvotes: 2

Views: 1017

Answers (2)

Neil Mitchell
Neil Mitchell

Reputation: 9250

The following seems to work:

public class MyComboBox : ComboBox
{
    public MyComboBox()
    {
        SetResourceReference(Control.StyleProperty, typeof(ComboBox));
    }
}

Upvotes: 3

Rohit Vats
Rohit Vats

Reputation: 81233

In case you want custom control to inherit theme template of base control, you have to

  1. Override defaultStyleKey metadata in static constructor of MyComboBox.
  2. Declare default template of your custom control under Themes/Generic.xaml folder and make sure it's based on style of ComboBox.
  3. You need to add Luna theme as resource dictionary under Themes/Generic.xaml merged dictionaries.

Declaration:

public class MyComboBox : ComboBox
{
    static MyComboBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyComboBox),
                           new FrameworkPropertyMetadata(typeof(MyComboBox)));
    }
}

Themes/Generic.xaml:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:YourNamespace"> <-- Replace namespace here
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary 
   Source="/PresentationFramework.Luna;component/themes/Luna.NormalColor.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <Style TargetType="local:MyComboBox"
           BasedOn="{StaticResource {x:Type ComboBox}}"/>

</ResourceDictionary>

Upvotes: 1

Related Questions