在WPF中,如何从合并字典中引用App.xaml中的StaticResource

Nai*_*der 5 c# wpf xaml uwp

这似乎是一个老问题:为什么我不能从合并的字典中引用 App.xaml 中的 StaticResource?这是我的代码:

应用程序.xaml:

<Application x:Class="WpfResources.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <Color x:Key="MyColor">GreenYellow</Color>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>

    </Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)

Dictionary1.xaml?

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <SolidColorBrush x:Key="Button.Static.Foreground" Color="{StaticResource MyColor}"/>

    <Style TargetType="{x:Type Button}">
        <Setter Property="Foreground"
            Value="{StaticResource Button.Static.Foreground}"/>
    </Style>
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

在设计时,一切都很好,我可以看到按钮的前景设置为 MyColor。但是在运行时,我得到了:

例外:找不到名为“MyColor”的资源。资源名称区分大小写。

顺便说一句:这些代码在 UWP 中工作,但在 WPF 中,似乎有所改变。我在网上做了很多搜索,找不到答案。

任何想法将不胜感激!谢谢!

(顺便说一句:我不想更改为 DynamicResource 解决方案)

编辑:为什么有人给我降级?有什么好的理由吗?虽然这是一个“老”的问题,但根据我的搜索,它仍然没有正确的答案!!

Evk*_*Evk 6

原因似乎是 xaml 解析器构建应用程序的顺序。首先它充满了MergedDictionaries。为此,它需要构造Dictionary1.xaml,此时它失败,因为还没有带有密钥的资源MyColor。要验证这一点,您可以在代码中按照正确的顺序自行填充资源:

this.Resources = new ResourceDictionary();
this.Resources.Add("MyColor", Colors.GreenYellow);
this.Resources.MergedDictionaries.Add(new ResourceDictionary() {Source = new Uri("Dictionary1.xaml", UriKind.Relative)});
Run Code Online (Sandbox Code Playgroud)

现在它会工作得很好。

当然,在代码中这样做不是一个选择(只是为了确认问题的根源)。作为解决方法,您可以执行以下操作:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary>
                <Color x:Key="MyColor">GreenYellow</Color>
            </ResourceDictionary>
            <ResourceDictionary Source="Dictionary1.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)

现在,xaml 解析器将首先将您的字典与资源合并,然后再将所有其他字典合并,因此MyColor所有这些字典都可用。

  • 这就是我想要的答案!我希望我早点看到这个答案!非常感谢先生,您救了我的命! (4认同)