在C#类库项目中使用(合并的)资源字典

3

我该如何在 C# 类库项目中使用合并的 WPF 资源字典?

以下是我的做法:

在我的 C# 类库项目中,我有一个名为 Dictionary1.xaml 的文件,内容如下:

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

然后,我有一个名为UserControl1.xaml的用户控件文件,在其中我尝试像这样使用字典:
<UserControl x:Class="EditorPackageA.BackboneMemberB1Editor.BackboneMemberB1Editor"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         xmlns:local="clr-namespace:EditorPackageA.EditorBase"
         xmlns:prism="http://www.codeplex.com/prism" d:DesignWidth="690.4" d:DesignHeight="460.12">
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Dictionary1.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
...
</UserControl>

该项目编译通过,但在运行时出现错误:

enter image description here

除了细节之外:

enter image description here

当应用于WPF项目而不是类库项目时,相同的方法也适用。

这里可能的解决方案是什么?

重要补充:

在设计时,我可以看到通过ResourceDictionary嵌入的使用样式的效果,因此样式和字典的URI必须正确!

3个回答

2

尝试使用所谓的打包URI。我认为您需要明确指定资源字典位于何处。

<ResourceDictionary Source="pack://application:,,,/TheNameOfClassLibrary;component/Dictionary1.xaml"/>

在WPF项目中,您的方法有效,因为WPF引擎默认在执行程序(exe)的程序集中查找资源。

0
你可能需要将库的资源字典合并到应用程序资源中。你需要编辑你的App.xaml文件,添加类似以下内容的代码:
<Application.Resources>
<ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Dictionary1.xaml" />
      </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>

0

您应该将ResourceDictionary xml文件与程序集和组件名称链接到Source属性中。
使用相对路径如下:

<ResourceDictionary Source="../Dictionary1.xaml" /> 

如果它不起作用,那么尝试 PACK URL。
<ResourceDictionary Source="pack://application:,,,/Your.Base.AssemblyName;component/DictionaryFolder/Dictionary1.xaml" />

希望能对你有所帮助

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接