【发布时间】:2017-05-20 04:34:38
【问题描述】:
我希望能够在 WPF 窗口中使用默认位图资源或由单独程序集提供的位图资源。我想我可以通过在 Window.Resources 部分中定义默认位图来做到这一点,然后搜索并如果从单独的可选程序集中找到资源,则加载:
[窗口的xaml文件]
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<BitmapImage x:Key="J4JWizardImage" UriSource="../assets/install.png"/>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
[窗口构造函数的代码]
try
{
var resDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Olbert.JumpForJoy.DefaultResources.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.Add( J4JWizardImageKey, j4jRD[ "J4JWizardImage" ] );
}
}
catch (Exception ex)
{
}
InitializeComponent();
但是,即使存在单独的资源程序集,也会始终显示默认图像。显然,在窗口定义中定义的资源优先于在构建窗口时添加的资源。
所以我删除了 Window.Resources 部分,添加了一个独立的资源 xaml 文件:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Olbert.Wix.views">
<BitmapImage x:Key="DefaultWizardImage" UriSource="../assets/install.png"/>
</ResourceDictionary>
并修改了窗口构造函数代码,以便如果未找到单独的程序集,则将添加独立 xaml 文件中的资源:
if( File.Exists( resDllPath ) )
{
// same as above
}
else
Resources.Add( J4JWizardImageKey, TryFindResource( "DefaultWizardImage" ) );
当存在单独的程序集时,此方法有效。但是,当单独的程序集被遗漏时,它失败了,因为没有找到默认的图像资源。这可能是因为这个窗口不是 WPF 应用程序的一部分;它是 Wix 引导程序项目的 UI。
感觉应该有一个更简单的解决方案来解决我正在尝试做的事情,我想这在设计 WPF 库时很常见(即,您需要某种方式来允许自定义位图,但您也想要提供默认/后备)。
【问题讨论】:
-
您是用
StaticResource还是DynamicResource检索它?StaticResource只是在解析 XAML 时获取那里的任何内容。DynamicResource会在资源变化时更新目标。 -
这就是问题所在!谢谢@EdPlunkett!如果您将其作为答案发布,我会将其标记为这样。