不应用 generic.xaml 中的样式 [英] Styles from generic.xaml are not applied

查看:21
本文介绍了不应用 generic.xaml 中的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个类库程序集,在其中创建了自定义控件,并在 generic.xaml 文件中定义了默认样式.

I made a class library assembly in which I created custom controls, and I defined the default styles in the generic.xaml file.

这似乎是一个很常见的问题,只要很多人都在发帖.但是我找不到任何对我的案例有用的答案.

It seems this is a quite common problem, as long as many people are posting about it. However I couldn't find any useful answer for my case.

  • generic.xaml 位于 Themes 文件夹中.
  • generix.xaml 文件构建操作设置为页面.
  • ThemeInfo 在我的 AssemblyInfo.cs 中正确定义.

在我的测试应用程序中,如果我手动将 generic.xaml 文件从我的自定义控件程序集中合并到应用程序 App.xaml 文件中,如下所示:

In my test application, if I manually merge the generic.xaml file from my custom controls assembly into the application App.xaml file like this:

<Application.Resources>
  <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="/MyControlsAssembly;component/Themes/generic.xaml"/>
    </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>

然后自定义控件的主题正确,但如果我不手动合并 generic.xaml,控件将显示为默认的 Windows 主题.

then the custom controls are properly themed, but if I do not manually merge the generic.xaml, the controls appear with the default Windows theme.

你能告诉我我忘记了什么和/或做错了什么吗?

Could you please tell me what am I forgetting and/or doing wrong ?

附加信息:

  • 我的 ThemeInfo 程序集属性定义如下:

  • My ThemeInfo assembly attribute is defined as follow:

[程序集:ThemeInfo(ResourceDictionaryLocation.SourceAssembly, ResourceDictionaryLocation.SourceAssembly)]

(注意:ThemeInfo 属性的任意参数组合的结果都是一样的)

(Note: the result is just the same with any combination of parameters for the ThemeInfo attribute)

Themes 文件夹中的 generic.xaml 文件旁边还有另外两个 .xaml 文件.

There are two others .xaml files beside the generic.xaml file in the Themes folder.

推荐答案

您的自定义控件构造函数中需要以下行:

You need the following line in your custom control constructor:

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

然后,如果您在 themes 文件夹中有一个 generic.xaml 文件,具有以下示例样式:

Then if you have a generic.xaml file inside themes folder, with the following sample style:

<Style TargetType="{x:Type local:MyCustomControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                <Border>
                    <Label>Testing...</Label>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

现在样式将自动应用,无需任何额外的合并.

Now the style will get automatically applied without any extra merging.

这篇关于不应用 generic.xaml 中的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆