在 WPF 窗口中包括可选资源



我希望能够使用默认位图资源或由 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 库时,这很常见(即,您需要某种方法来允许自定义位图,但您还希望提供默认值/回退)。

听起来你只会从分析 XAML 时获取资源的初始值。如果当时它不存在,那就什么都没有;如果它是一个东西,那么它只是那个东西。

这是使用StaticResource而不是DynamicResource检索资源时将看到的行为。DynamicResource将在替换资源时更新目标。

<Label Content="{DynamicResource MyImageSomewhere}" />

最新更新