WPF创建单独资源库并在应用中引用

主要目的:

1.如何把WPF中的资源集中管理放到单独的程序集中,方便资源共享

2.主应用如何引用资源库中资源

  

  废话不多说:

  1.创建WPF类库(WPFTest.Res)作为资源库并创建相应文件,如下图(创建WPFUI类库把不需要的删除也可以)

  

  2.创建类型 MyResource.cs 目前这个类除了改成Public外不需要添加其它代码

  3.编写Themes/generic.xaml中的内容 注意的是x:key中的内容在Vs2013智能提示不出来,直接照打即可 ComponentResourceKey 用于定义 组件的资源键,指定ResourceId 有点注意的是 在根节点引用相应项目的命名空间 xmlns:local="clr-namespace:你的项目名称",图片等资源文件“生成操作”需要指定为“资源(Resource)”,可能ImageSource等引用中会在编辑器中提示找不到文件,但只要符合规定来设置不影响使用

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WPFTest.Res">
    <ImageBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:MyResource},ResourceId=SadTitleBrush}"
                TileMode="Tile"
                ImageSource="WPFTest.Res;component/Img/timg.jpg">
    </ImageBrush>
    <SolidColorBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:MyResource},ResourceId=MyColorBrush}"
                     Color="Blue">
    </SolidColorBrush>
</ResourceDictionary>

  4.MyResource.cs中添加以下静态变量简化资源引用

    public static class MyResource
    {
        public static ComponentResourceKey MyColorBrushKey
        {
            get
            {
                return new ComponentResourceKey(
                    typeof(MyResource), "MyColorBrush");
            }
        }

        public static ComponentResourceKey SadTitleBrushKey
        {
            get
            {
                return new ComponentResourceKey(
                    typeof(MyResource), "SadTitleBrush");
            }
        }
    }

  5.创建一个空白的WPF项目,并添加资源类库的引用 打开 MainWindow.xaml 添加以下代码引用资源库内的资源。引用资源前需要根据项目设置引用的命名空间  xmlns:res="clr-namespace:资源库命名空间;assembly=资源库程序集名称"

<Window x:Class="WPFTest.ResHost.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:res="clr-namespace:WPFTest.Res;assembly=WPFTest.Res"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button Content="测试" Background="{DynamicResource {x:Static res:MyResource.MyColorBrushKey}}" ></Button>
        <Button Content="测试2" Background="{DynamicResource {x:Static res:MyResource.SadTitleBrushKey}}"></Button>
    </StackPanel>
</Window>

最终效果:

示例代码下载:

 https://files.cnblogs.com/files/nekoyzx/WPFTest.Res.7z

原文地址:https://www.cnblogs.com/nekoyzx/p/7599492.html