从不同程序集加载合并的ResourceDictionary失败

本文关键字:ResourceDictionary 失败 合并 加载 程序集 | 更新日期: 2023-09-27 18:17:40

我已经把所有应用程序的ResourceDictionary放到一个单独的程序集中,并将它们合并成一个ResourceDictionary,我想把它作为一个资源包含在我的应用程序中:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="InputStyles.xaml"/>
        <ResourceDictionary Source="DataGridStyles.xaml"/>
        <ResourceDictionary Source="ComboboxStyles.xaml"/>
        <ResourceDictionary Source="CheckboxStyles.xaml"/>
        <ResourceDictionary Source="TabControlStyles.xaml"/>
        <ResourceDictionary Source="ButtonStyles.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

声明资源:

<Window.Resources>
    <ResourceDictionary Source="pack://application:,,,/StyleAssembly;component/Styles.xaml"/>
</Window.Resources>

查看VS中的设计器,所有控件都显示了文件中的样式,但当我尝试启动应用程序时,我得到以下错误:

"无法找到资源'inputstyles.xaml'."

构建操作被设置为所有文件的'Page',并且两个项目的构建都成功。我做错了什么?

从不同程序集加载合并的ResourceDictionary失败

如果您愿意做一些腿部工作,则构建操作应该定义为资源或内容。

您的资源必须作为资源定义为项目的一部分建立行动。如果您将资源.xaml文件包含在项目中资源,则不需要将资源文件复制到输出中目录中,资源已包含在已编译的应用程序。您也可以使用内容构建操作,但必须这样做将文件复制到输出目录,并部署资源与可执行文件有相同路径关系的文件。

据我观察。将资源字典构建样式设置为Resource可能会导致进一步的奇怪错误(我突然开始获得运行时错误Cannot create X,其中X是我的资源字典中引用的用户定义类型)。

我建议将构建风格保留在Page。从我所看到的,这应该工作得很好

关于WPF中包uri的更多细节;合并资源字典

Build action应该是Resource

当您知道外部Assembly结构(文件名等)和,当你不知道,只是想为ResourceDictionary(s)或迭代外部AssemblyUserControls

Both XMAL and C# solution.

更新

XAML方式:If you know the URI of the resource in an Assembly, then load it directly. Transform same syntax in XAML

ResourceDictionary dictionary = new ResourceDictionary();
 dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
 foreach (var item in dictionary.Values)
 {
    //operations
 }
c#方式:If you only know the Assambly and don't know the Resources in it
public ResourceDictionary GetResourceDictionary(string assemblyName)
{
    Assembly asm = Assembly.LoadFrom(assemblyName);
    Stream stream = asm.GetManifestResourceStream(asm.GetName().Name + ".g.resources");            
    using (ResourceReader reader = new ResourceReader(stream))
    {
        foreach (DictionaryEntry entry in reader)
        {
            var readStream = entry.Value as Stream;
            Baml2006Reader bamlReader = new Baml2006Reader(readStream);
            var loadedObject = System.Windows.Markup.XamlReader.Load(bamlReader);
            if (loadedObject is ResourceDictionary)
            {
                return loadedObject as ResourceDictionary;
            }
        }
    }
    return null;
}
相关文章:
  • 没有找到相关文章