在 UserControl 库中使用全局 ResourceDictionary,而不在 UserControl 中引用它

问题描述 投票:0回答:1

我创建了一个包含多个用户控件的 WPF 类库项目。我想定义库中所有用户控件都可以共享和引用的通用样式、模板和资源。

我尝试在程序集级别(在 Themes/Generic.xaml 中)定义 ResourceDictionary,但在 UserControls 中使用时找不到资源。

例如,在 Themes/Generic.xaml 中:

<ResourceDictionary 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <SolidColorBrush x:Key="TextColorBrush" Color="Blue"/>
</ResourceDictionary>

然后在用户控件之一中:

<UserControl
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">

  <TextBlock Text="Hello" Foreground="{StaticResource TextColorBrush}"/>

</UserControl>

这将导致编译时错误,因为如果没有显式引用全局资源字典,则无法解析资源。

有没有一种方法可以定义全局资源,以便它们在整个程序集/项目中隐式可用,而无需在每个用户控件中包含 ResourceDictionary?

理想情况下,我不希望每个控件都必须包含:

<UserControl.Resources>
  <ResourceDictionary Source="Themes/Generic.xaml"/>
</UserControl.Resources>

如有任何建议,我们将不胜感激!

c# .net wpf resourcedictionary
1个回答
0
投票

您可以将资源放入您的app.xaml文件中:

    <Application.Resources>
         <ResourceDictionary>
             <ResourceDictionary.MergedDictionaries>
                 <!-- Merged dictionaries -->
            </ResourceDictionary.MergedDictionaries>
            <!-- Other resources -->
          </ResourceDictionary>
    </Application.Resources>

这应该使资源可用于同一应用程序中的所有控件。

老实说,我不知道在建立图书馆时应该做什么。我试图找到一些关于在编写库时如何最好地管理样式和其他资源的指导,但有些指导却是空的。

© www.soinside.com 2019 - 2024. All rights reserved.