首页 文章

在WPF窗口中包含可选资源

提问于
浏览
0

我希望能够使用默认位图资源或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定义中定义的资源优先于构造窗口时添加的资源 .

所以我删除了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库设计(即,你需要一些方法来允许自定义位图,但你也想提供一个默认/备用) .

1 回答

  • 1

    听起来你只是获得资源的初始值,就像解析XAML时一样 . 如果当时不存在,那就没有了;如果这是一件事,它只是那件事 .

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

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

相关问题