样式继承了控件,如基本控件

时间:2014-01-31 12:05:47

标签: c# wpf inheritance

在WPF / C#中,我想定义一个继承自现有控件的新类,但它使用基本控件的样式。例如:

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

我通过以下方式动态切换到Luna风格:

 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;

虽然这样可以正确地为ComboBox Luna主题的所有实例设置样式,但MyComboBox控件最终会显示经典主题。如何让MyComboBoxComboBox继承其样式?

我在代码中编写所有WPF,而不使用XAML标记。我怀疑StyleBasedOn属性是相关的,但我还没弄清楚究竟是怎么做的。

2 个答案:

答案 0 :(得分:3)

以下似乎有效:

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

答案 1 :(得分:1)

如果您希望自定义控件继承基本控件的主题模板,则必须

  1. Override defaultStyleKey metadata 在MyComboBox的静态构造函数中。
  2. Themes/Generic.xaml 文件夹下声明自定义控件的默认模板,并确保它基于ComboBox的样式。
  3. 您需要在 Themes/Generic.xaml 合并词典下添加Luna主题作为资源词典。
  4. <强>声明:

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

    <强>主题/ 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>