【问题标题】:Pack URI to resources in referenced assembly将 URI 打包到引用程序集中的资源
【发布时间】:2013-12-10 21:34:22
【问题描述】:

我已经为此苦恼了一段时间,但看在上帝的份上,我就是不知道我的 uri 出了什么问题。也许有人可以帮忙。

我正在为第三方软件开发插件(意味着我无法访问 App.config 并且无法修改应用程序本身)。插件位于与 exe 文件位置不同的文件夹中。我有一个位于 MyAddin.View.dll 中的 wpf 窗口。最近我决定将所有 WPF 资源移动到一个单独的程序集中(称为 UI.Shared)。我添加了 UI.Shared.dll 作为对 MyAddin.View.dll 的引用,我还在 MyAddin.View.dll 窗口中修改了我的包 uri:

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

</Window.Resources>

我已确保将 Style.xaml 构建操作设置为资源。 UI.Shared.dll 与 MyAddin.View.dll 位于同一文件夹中(但它们都 NOT 与应用程序可执行文件位于同一文件夹中)。在设计时一切正常。但在运行时,我得到:

“Set property 'System.Windows.ResourceDictionary.Source' throw an exception。”
内部异常说:

无法加载文件或程序集“UI.Shared,Culture=neutral”或其依赖项之一。系统找不到指定的文件。

在我将资源移动到单独的程序集中之前,一切正常:(。有人可以帮忙吗?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    你的 URI 没问题。

    我在从 VBA 调用 WPF 窗口时遇到了类似的问题:WPF 无法找到引用的资源,因为主进程是从不同的目录启动的。我发现的解决方案可能对您的情况也有用:

    这里是一些(未经测试的)C# 示例代码,灵感来自我们在生产中使用的一些 VB.NET 代码:

    // Do this when your add-in starts
    var addinAssembly = Assembly.GetExecutingAssembly();
    
    AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
    {
        var missing = new AssemblyName(e.Name);
    
        // Sometimes the WPF assembly resolver cannot even find the executing assembly...
        if (missing.FullName == addinAssembly.FullName)
            return addinAssembly;
    
        var addinFolder = Path.GetDirectoryName(addinAssembly.Location);
        var missingPath = Path.Combine(addinFolder, missing.Name + ".dll");
    
        // If we find the DLL in the add-in folder, load and return it.
        if (File.Exists(missingPath))
            return Assembly.LoadFrom(missingPath);
    
        // nothing found
        return null;
    };
    

    【讨论】:

    • 嗯,这行得通,但我希望有一个更清洁的解决方案。如果没有,我会将其标记为答案。
    • 这是我见过的最干净的 AssemblyResolve 实现。 :)
    猜你喜欢
    • 2011-03-13
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2023-03-11
    • 2014-07-26
    • 2012-01-02
    • 1970-01-01
    相关资源
    最近更新 更多