【问题标题】:How to match WPF custom control to the app theme when the app theme is not the default theme?当应用主题不是默认主题时,如何将 WPF 自定义控件与应用主题匹配?
【发布时间】:2011-07-01 13:49:20
【问题描述】:

我正在制作从 ComboBox 派生的自定义控件,但在主题化方面遇到了一些困难。我可以毫无困难地让它采用当前的 OS 主题,但是当我在 App.xaml 中明确加载新主题时,我的派生控件仍会显示 OS 主题。

我可以用最少的代码重现问题:

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

然后在 Themes/generic.xaml 中:

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

到目前为止一切顺利——MyComboBox 显示正确,并且与当前主题相匹配。

但是当我添加到我的 App.xaml 时:

<ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/PresentationFramework.Luna;V3.0.0.0;31bf3856ad364e35;component\themes/luna.normalcolor.xaml" />
  </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

...常规的 ComboBox 将显示 Luna chrome,但 MyComboBox 将继续显示当前主题(在我的情况下是 Aero,但我也使用 Classic 进行了测试)。

我尝试将 MyComboBox 的 (在我的测试应用中与 ThemeInfoAttribute 错误)。

我已经确认它是从 aero.normalcolor.xaml(我的操作系统正在使用的主题)而不是从 luna.normalcolor.xaml(我在我的 App.xaml 中指定的主题)加载样式。

谁能指出我正确的方向?还是我试图做的事情是不可能的?谢谢!

【问题讨论】:

    标签: wpf controls themes inheritance


    【解决方案1】:

    您是否指定了 ThemeInfo 属性的正确设置是 AssemblyInfo.cs?

    【讨论】:

    • 实际上,我有 ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly),这解释了为什么只加载了 generic.xaml。现在我已经解决了这个问题,它会从其他 XAML 文件加载样式,但我的控件仍然与应用程序主题不匹配。
    • 我已经确认它从 Themes/aero.normalcolor.xaml(我的操作系统正在使用的主题)而不是 Themes/luna.normalcolor.xaml(我在我的应用程序中选择的主题)加载样式.xaml)。
    【解决方案2】:

    这只是一个猜测,但如果您改用 DynamicResource 会怎样?

    【讨论】:

      猜你喜欢
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      相关资源
      最近更新 更多