Windows应用商店应用 - 资源字典样式问题

时间:2013-08-21 02:05:27

标签: windows microsoft-metro resourcedictionary

在Windows应用商店应用中,我无法通过StaticResource绑定将一个资源字典中的资源用作第二个资源字典样式中的属性设置器的值。

以下是我正在尝试做的一个例子:

Dictionary1.xaml

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

    <SolidColorBrush x:Key="SomeBrush" Color="Black" />
</ResourceDictionary>

Dictionary2.xaml

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

    <Style x:Key="SomeStyle" TargetType="Button">
        <Setter Property="Foreground" Value="{StaticResource SomeBrush}" />
    </Style>
</ResourceDictionary>

的App.xaml

<Application
    x:Class="TestApp.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Common/StandardStyles.xaml"/>
                <ResourceDictionary Source="Common/Dictionary1.xaml"/>
                <ResourceDictionary Source="Common/Dictionary2.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

无论我做什么,这都行不通。该应用程序将无法启动,而是抛出一个未处理的异常,导致无法找到“带有密钥'someBrush'的资源”。

我尝试更改App.xaml中的顺序,使用嵌套的合并字典等等。

已经通过这样做设法让它工作,但这不是一个选项:

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

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

    <Style x:Key="SomeStyle" TargetType="Button">
        <Setter Property="Foreground" Value="{StaticResource SomeBrush}" />
    </Style>
</ResourceDictionary>

在运行时,将清除App.Resources.MergedDictionaries,并根据各种条件动态加载各种资源字典。 Dictionary1.xaml和Dictionary2.xaml彼此独立地加载,并且可以根据这些条件包含不同的资源,因此以这种方式合并它们不是一种选择。它们必须在设计时包含在App.xaml中才能支持.... design。

有谁知道这里发生了什么?这是一个错误吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

我相信我理解这里发生的事情,我会尝试解释我的观点,希望它会有所帮助。

从我所看到的,在玩完并能够复制您看到的问题之后,它看起来好像使用StaticResource关键字意味着它所指的密钥需要在ResourceDictionary的“范围”。

这可以解释为什么您的第二次尝试有效,因为您已将Dictionary1.xamlDictionary2.xaml合并,因此SomeBrush可以被视为“在范围内”并且它可以正常工作。

显然,在第一种情况下,Dictionary1.xaml中定义的密钥被视为Dictionary2.xaml的“超出范围”。但它将被视为应用程序的“范围”。

我基于我观察到的内容基于此,但我也在MSDN的ResourceDictionary and XAML resource references页面中找到了以下句子:

  

在ResourceDictionary的范围内,检查字典是否具有密钥唯一性。但是,该范围不会扩展到MergedDictionaries中的不同项目。

答案 1 :(得分:0)

我今天遇到了与Universal App Project类似的问题。问题是,合并的词典需要Source - 路径和ms-appx - 协议。

<ResourceDictionary Source="ms-appx:///Common/StandardStyles.xaml"/>
...

它能解决你的问题吗?

相关问题