【问题标题】:Style inherited control like base control样式继承控件,如基本控件
【发布时间】:2014-01-31 12:05:46
【问题描述】:

在 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;

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

我正在用代码编写我所有的 WPF,而不使用 XAML 标记。我怀疑 StyleBasedOn 属性是相关的,但我还没有弄清楚到底是怎么回事。

【问题讨论】:

    标签: c# wpf inheritance


    【解决方案1】:

    以下似乎有效:

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

    【讨论】:

      【解决方案2】:

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

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

      声明:

      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>
      

      【讨论】:

        猜你喜欢
        • 2011-12-04
        • 2021-10-30
        • 2016-10-11
        • 2023-03-25
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-10
        相关资源
        最近更新 更多