简体   繁体   中英

How to match WPF custom control to the app theme when the app theme is not the default theme?

I'm making a custom control derived from ComboBox, and I'm having some difficulty with theming. I'm able to get it to adopt the current OS theme without any difficulty, but when I explicitly load a new theme in my App.xaml, my derived control still displays with the OS theme.

I can reproduce the problem with a minimal set of code:

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

And then in Themes/generic.xaml:

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

So far so good -- MyComboBox displays correctly, and matches the current theme.

But then when I add to my App.xaml:

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

...a regular ComboBox will display Luna chrome, but MyComboBox will continue to display the current theme (Aero, in my case, but I've tested with Classic too).

I've tried adding the <Style> tag for MyComboBox to Themes/luna.normalcolor.xaml and the other theme XAML files, with no effect -- only the <Style> from generic.xaml is loaded, no matter what theme I've specified in App.xaml. (mistake with ThemeInfoAttribute in my test app).

I've confirmed that it's loading the Style from aero.normalcolor.xaml (the theme my OS is using) rather than from luna.normalcolor.xaml (the theme I've specified in my App.xaml).

Can anybody point me the right direction? Or is what I'm trying to do not possible? Thanks!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM