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

时间:2017-06-10 03:22:53

标签: c# wpf xaml uwp

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

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

Dictionary1.xaml:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true,
        "baseUrl": "./src",
        "outDir": "compiled",
        "paths": {},
        "lib": [
            "es2015",
            "dom"
        ],
        "typeRoots": [
            "node_modules/@types"
        ]
    },
    "exclude": [
        "node_modules",
        "dist",
        "compiled",
        "src/**/*.spec.ts",
        "src/**/*.e2e.ts"
    ],
    "awesomeTypescriptLoaderOptions": {
        "forkChecker": true,
        "useWebpackText": true
    },
    "angularCompilerOptions": {
        "genDir": "compiled",
        "skipMetadataEmit": true
    },
    "compileOnSave": false,
    "buildOnSave": false,
    "atom": {
        "rewriteTsconfig": false
    }
}

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

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

不过:这些代码在UWP中有效,但在WPF中,似乎有些变化。我在网上做了很多搜索,找不到答案。

任何想法都将不胜感激! THX!

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

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

2 个答案:

答案 0 :(得分:1)

原因似乎是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 :(得分:0)

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

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


2。另一种方式

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

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

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

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

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

<Setter Property="Property" Value="{TemplateBinding Foreground}"/>
相关问题