我有一个WPF用户控件,该控件定义了一些默认样式和图像,我希望能够在运行时使用资源组装中包含的自定义样式和图像来覆盖它们。在运行时合并WPF ResourceDictionary
的风格和图像都包含在一个装配体中的命名Olbert.JumpForJoy.DefaultResources称为DefaultResources.xaml的ResourceDictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="J4JResources">
<BitmapImage x:Key="J4JMessageBoxImage" UriSource="assets/j4jmsgbox.png" />
<BitmapImage x:Key="J4JWizardImage" UriSource="assets/j4jtransparent.png" />
<Color x:Key="J4JButton0Color">#bb911e</Color>
<Color x:Key="J4JButton1Color">#252315</Color>
<Color x:Key="J4JButton2Color">#bc513e</Color>
<Color x:Key="J4JButtonHighlightColor">Orange</Color>
</ResourceDictionary>
为了提供这样的一个应用程序,我想补充创建时该资源的NuGet包项目编译到使用自定义资源的应用程序。我已经确认dll被添加到目标bin目录。
我尝试加载自定义资源装配在App.xaml.cs文件中,OnStartup()方法中:
public partial class App : Application
{
public const string ResourceDll = "Olbert.JumpForJoy.DefaultResources";
protected override void OnStartup(StartupEventArgs e)
{
try
{
var resDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ResourceDll}.dll");
if (File.Exists(resDllPath))
{
var resAssembly = Assembly.LoadFile(resDllPath);
var uriText = $"pack://application:,,,/{resAssembly.GetName().Name};component/DefaultResources.xaml";
ResourceDictionary j4jRD = new ResourceDictionary {
Source = new Uri(uriText)
};
Resources.MergedDictionaries.Add(j4jRD);
}
}
catch (Exception ex)
{
}
}
}
但在创建资源字典时,一个异常被抛出。该消息是“无法找到资源defaultresources.xaml'”。
我已经尝试了很多uri定义的调整来解决这个问题,但都没有工作。资源程序集是版本控制的,但是否在uri定义中包含特定的版本,我得到了同样的错误。
如果将可选资源组合合并到WPF项目中有不同的方式,我很乐意听到它。我的具体问题的答案,将不胜感激,太:)
更新
如果我试图通过App.xaml中做到这一点:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Olbert.JumpForJoy.DefaultResources;component/DefaultResources.xaml" />
<ResourceDictionary Source="NotifyIconResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
我得到一个设计时错误“找到资源字典时发生错误...“
在我的原始方法中调用resAssembly.GetManifestResourceNames()显示资源确实存在于自定义程序集中。但他们似乎组装的默认命名空间“下”:
Olbert.JumpForJoy.WPF.DefaultResources.xaml
这使我想知道如果我需要指定该命名空间,不知何故,在定义乌里。
如果直接在您的合并外部资源是否错误出现'''中App.xaml'? –
Maxim