【问题标题】:winrt xaml merged resourceswinrt xaml 合并资源
【发布时间】:2012-10-21 19:33:48
【问题描述】:

我需要将应用程序样式分成几个 xaml 文件。 但我还需要定义一些共享值,例如

<x:Double x:Key="SharedValue">100</x:Double>

在单个文件中用于在其他文件中定义的样式中使用此值。 例如:

<Style x:Name="SomeStyle" TargetType="TextBox">
     <Setter Property="Width" Value="{StaticResource SharedValue}"/>
</Style>

在另一个资源字典文件中:

<Style x:Name="AnotherStyle" TargetType="Button">
     <Setter Property="Height" Value="{StaticResource SharedValue}"/>
</Style>

但是当我尝试在 App.xaml 文件中定义合并的资源字典时

<Application.Resources>
    <ResourceDictionary >
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="DefinedValues.xaml"/>
            <ResourceDictionary Source="Styles1.xaml"/>
            <ResourceDictionary Source="Styles2.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

我得到这个运行时异常:"Message = "Cannot find a Resource with the Name/Key SharedValue"

你能告诉我这样做是否可行以及我做错了什么? 谢谢。

【问题讨论】:

  • 您在哪里看到的消息?您是否尝试使用 {StaticResource} 访问 XAML 中的资源?
  • 当它在 App.g.i.cs 文件中作为运行时未处理的异常处理时出现此错误,但智能不会将我的 SharedValue 点亮为无法在任何地方识别。
  • 是的,这是可能的,我能够使用您的示例创建一个应用程序,它适用于我的项目。您确定您的 App.xaml 文件中有 DefinedValues.xaml 和其他两个 ResourceDictionaries 的正确路径吗?
  • 路径是正确的,但我有几个我不知道的错误。第一个是我在声明字典的顺序上犯了错误,第二个是我没有在依赖字典中引用 SharedValues 字典。在我纠正这些错误后,一切正常。谢谢,你帮了我!

标签: xaml windows-runtime resourcedictionary mergeddictionaries


【解决方案1】:

如果您在其他合并词典之间存在依赖关系,使用合并词典可能会有些棘手。

当您有多个应用程序范围的资源时,声明的顺序很重要。它们以声明的相反顺序解决,因此在您的情况下,您应该有顺序。

<Application.Resources>
<ResourceDictionary >
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Styles1.xaml"/>
        <ResourceDictionary Source="Styles2.xaml"/>
        <ResourceDictionary Source="DefinedValues.xaml"/>

    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

此外,您可能需要引用 Styles1.xaml 中的其他 ResourceDictionary。这在 Styles1.xaml 中对我有用。

<ResourceDictionary "...">

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

  <Style x:Name="AnotherStyle"
         TargetType="Button">
    <Setter Property="Height"
            Value="{StaticResource SharedValue}" />
  </Style>
</ResourceDictionary>

【讨论】:

  • 谢谢,这正是我想要的!
  • 仅供参考,当你得到一个可以接受的答案时,你可以投票赞成这个答案,但你也应该“接受”这个答案。这样一来,您在 StackOverflow 上的声誉就会提高,而且人们将来更有可能帮助您。
  • 第二部分是重要的部分。在我的情况下,文件的顺序并不重要,但在我的模板中注册样式确实很有帮助。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 2011-02-07
相关资源
最近更新 更多