C# 在WPF中,如何从合并字典中引用App.xaml中的StaticResource
这似乎是一个老问题:为什么我不能从合并字典中引用App.xaml中的StaticResource?这是我的密码: App.xaml:C# 在WPF中,如何从合并字典中引用App.xaml中的StaticResource,c#,wpf,xaml,uwp,C#,Wpf,Xaml,Uwp,这似乎是一个老问题:为什么我不能从合并字典中引用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
<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>
绿黄色
字典1.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中,似乎有些变化。我在网上做了很多搜索,找不到答案
任何想法都将不胜感激!谢谢
(顺便说一句:我不想更改为DynamicSource解决方案)
编辑:
为什么有人给我降级?有什么好的理由吗?
虽然这是一个“老”问题,但根据我的搜索,它仍然没有正确的答案 一,。也许申报的优先顺序是错误的
它可能有用:
2.另一种方式 我认为在页面中定义颜色很好:
<SolidColorBrush x:Key="MyColor" Color="#fff"/>
然后将前景按钮绑定到这些页面颜色资源:
<Button Foreground="{DynamicResource MyColor}"/>
在资源字典中,绑定您需要的每个属性:
<Setter Property="Property" Value="{TemplateBinding Foreground}"/>
原因似乎是xaml解析器构造应用程序的顺序。首先,它填充
合并词典
。要做到这一点,它需要构造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
将可供所有字典使用。thx!但我相信解决方案1只适用于UWP(尽管我还没有测试过)。至于2,我不想使用动态资源。我的App.xaml中有很多样式,我想将它们移到单独的资源字典中,所以我真的想让我的方法发挥作用。链接可能会有帮助:完整描述在:事实上,根据Evk的回答,我将“MyColor”移到另一个资源字典中,并将其合并到App.xaml中(在Dictionary1.xaml之前),然后一切都起作用了。这与解决方案1类似,但您没有提到它的工作原理,因此我无法将此答案标记为已接受。很抱歉但是谢谢!这就是我想要的答案!我要是早点看到这个答案就好了!非常感谢,先生,你救了我的命!