繁体   English   中英

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

[英]In WPF, how to reference a StaticResource in App.xaml from merged dictionary

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

App.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>

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>

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

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

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

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

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

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

原因似乎是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)});

现在它会正常工作。

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

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary>
                <Color x:Key="MyColor">GreenYellow</Color>
            </ResourceDictionary>
            <ResourceDictionary Source="Dictionary1.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

现在,xaml解析器将首先将您的字典与资源以及所有其他字典合并,因此MyColor将可供所有这些字典使用。

1.声明的优先权可能是错误的

它可能很有用: can-merged-resource-dictionaries-access-resources-from-app-xaml


另一种方式

我认为在页面中定义颜色很好:

<SolidColorBrush x:Key="MyColor" Color="#fff"/>

然后将按钮前景绑定到那些页面颜色资源:

<Button Foreground="{DynamicResource MyColor}"/>

并在资源字典中 ,绑定您需要的每个属性

<Setter Property="Property" Value="{TemplateBinding Foreground}"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM