我已经为此苦恼了一段时间,但看在上帝的份上,我就是不明白我的 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>
Run Code Online (Sandbox Code Playgroud)
我已确保 Style.xaml Build Action 设置为 Resource。UI.Shared.dll 与 MyAddin.View.dll 位于同一文件夹中(但它们与应用程序可执行文件不在同一文件夹中)。设计时一切正常。但在运行时,我得到:
“设置属性‘System.Windows.ResourceDictionary.Source’抛出异常。”
内部异常表示:
无法加载文件或程序集“UI.Shared,Culture=neutral”或其依赖项之一。该系统找不到指定的文件。
在我将资源移动到单独的程序集中之前,一切都工作正常:(。有人可以帮忙吗?
你的 URI 没问题。
从 VBA 调用 WPF 窗口时,我遇到了类似的问题:WPF 无法找到引用的资源,因为主进程是从不同的目录启动的。我发现的解决方案可能对您的情况也有用:
AppDomain.AssemblyResolve事件。如果未找到该程序集,请在加载项目录中搜索它。下面是一些(未经测试的)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;
};
Run Code Online (Sandbox Code Playgroud)