You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在UserControl类库中全局使用ResourceDictionary无需逐个引用

WPF类库全局资源隐式可用解决方案

方法一:通过程序集属性注册全局资源

  • 在类库中创建一个存放通用资源的字典文件,比如Resources/SharedResources.xaml,将你的全局资源(如TextColorBrush)定义在这里:
    <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>
    
  • 设置该字典文件的生成操作为Resource(右键文件→属性→生成操作)。
  • 打开类库的Properties/AssemblyInfo.cs,添加ThemeInfo特性,指定通用资源的位置:
    using System.Windows;
    
    [assembly: ThemeInfo(
        ResourceDictionaryLocation.None, // 无需主题特定资源时设为None
        ResourceDictionaryLocation.SourceAssembly // 通用资源从当前程序集加载
    )]
    
    这样程序集内的所有UserControl就能直接通过{StaticResource TextColorBrush}引用全局资源,无需手动添加字典引用。

方法二:基于基类UserControl共享资源

  • 创建一个继承自UserControl的基类,比如BaseUserControl,在其XAML中合并全局资源字典:
    <UserControl x:Class="YourLibrary.BaseUserControl"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <UserControl.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="/YourLibrary;component/Resources/SharedResources.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </UserControl.Resources>
    </UserControl>
    
  • 让类库中所有的UserControl都继承这个BaseUserControl,而非默认的UserControl。
    这种方式无需修改程序集属性,通过继承实现资源共享,适合需要对基类做更多统一处理的场景。

注意事项

  • 确保资源字典的路径正确,格式为/程序集名称;component/资源文件路径,程序集名称需与类库项目名称一致。
  • Themes/Generic.xaml仅用于自定义控件(继承自Control的自定义类)的默认样式,不能直接作为全局资源供普通UserControl隐式引用,因此不推荐用它存放通用资源。

内容的提问来源于stack exchange,提问作者Dani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:55:14