获取要控件的 WPF 自定义控件库以显示正确样式的正确方法是什么?



我第一次涉足 WPF 自定义控件库池。我在单独的解决方案中为我的自定义控件创建了一个项目,该控件仅派生自 Control。

在我想使用自定义控件的目标应用中,它可以工作,但似乎无法访问默认样式,除非我在 App.xaml 文件中专门添加引用。我添加了 xmlns 属性,以便控件本身可用。我希望我缺少一些使控件更加独立的设置。因此,在我的目标 WPF 应用程序中,如果我在 App.xaml 中的注释后添加显示的行,一切正常(功能和样式):

    <Application.Resources>
     <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyStandardStuff.xaml" />
            <!-- How do I avoid having everyone who uses the control having to add the following line?-->
            <ResourceDictionary Source="/MyNewControl;component/Themes/Generic.xaml" />
        </ResourceDictionary.MergedDictionaries>
     </ResourceDictionary>
</Application.Resources>

假设我的自定义控件库有一个主题文件夹,其中包含包含以下样式的 Generic.xaml 文件:

<Style TargetType="{x:Type local:MyNewControl}">
 <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyNewControl}">
  ...

有没有办法在不添加 App.xaml 中显式引用的情况下使其工作?

编辑

下面是使用项目创建的 ThemeInfo 属性。

[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page, 
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page, 
// app, or any theme specific resource dictionaries)
)]

关于答案的细节

不确定这个问题是否会再次出现,因为事实证明我做了一些愚蠢的事情,但万一它确实如此......我使用 VS 模板创建了 WPF 自定义控件库。然后,我将我的控件类复制并粘贴到Visual studio创建的默认类上。我没有注意到的是,VS 创建了一个静态构造函数,它正在做一些非常重要的事情。在对以下答案的评论中指出了这一点。静态构造函数应如下所示

    static MyNewControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyNewControl),
            new FrameworkPropertyMetadata(typeof(MyNewControl)));
    }

一旦它到位,我就可以删除我添加到目标资源字典中的代码。

我会确保控件程序集中的 xaml 文件标记为 Page,并确保控件程序集的程序集信息中具有 ThemeInfo 属性.cs。

最新更新