【问题标题】:WP7 Mango ResouceDictionary MergedDictionariesWP7 Mango ResouceDictionary MergedDictionaries
【发布时间】:2012-04-03 07:23:20
【问题描述】:

我在 WP7 Mango 中遇到 ResourceDictionary 的问题。

我可以在互联网上找到的大部分内容都这么简单:

1) 带有正文的 Xaml 文件:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Style x:Key="TextBlockStyle1" TargetType="TextBlock">
 <Setter Property="Foreground" Value="Orange"/>
 <Setter  Property="FontSize" Value="24"/>
 <Setter  Property="VerticalAlignment" Value="Bottom"/>
</Style>
</ResourceDictionary>

2) 将以下内容添加到 App.xaml:

 <Application.Resources>
    <ResourceDictionary>
       <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="MyResources.xaml"/>
       </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
 </Application.Resources>

不知道为什么它不起作用。这样做时,我得到异常:

“ResourceDictionary”类型位于 ResourceDictionary 内部,没有键。

当我在步骤 2 中将 ked 添加到第二个 xaml 行时,它会运行,但会因未指定的错误而崩溃。看起来它没有从 MyResources.xaml 文件中添加资源。

有人可以在这里指出解决方案吗?

【问题讨论】:

  • 首先,确保文件“MyResources.xaml”存在且其“Build Action”设置为“Resource”
  • 我不认为资源需要作为构建操作,因为我只是在页面构建操作上运行它

标签: windows-phone-7 resourcedictionary mergeddictionaries


【解决方案1】:

您需要在 App.xaml 中为 ResourceDictionary 设置一个键。

<Application.Resources>
    <ResourceDictionary x:Key="keyname">
       <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="MyResources.xaml"/>
       </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

【讨论】:

  • 正如我在问题文本中所写的那样,我尝试添加效果不佳
  • 我刚刚意识到您的 Source 没有正确的格式。应该是Source="/{projectname};component/MyResource.xaml"。更多详情here
  • 我在项目中有 Xaml,像我一样调用它就足够了(我让它运行了,但由于某种原因我的答案没有在这里发布)
【解决方案2】:

其实想通了。

我试图让它在没有密钥的情况下工作,并发现我留在 App.xaml 中的样式造成了问题。因此,App.xaml 中剩下的所有样式我都必须移到里面,即使它们是独一无二的。

<Application.Resources>
<ResourceDictionary>

   my remaining styles with key & target type are here now

   <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="MyResources.xaml"/>
   </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>

编辑:

一些更重要的细节可能会节省一些人的时间,我花了很长时间才弄清楚: 1) 正如 MSDN 所建议的那样,您不应将 Key 放入 ResourceDictionary

2) 引用的 Xaml 中的样式都应包含 Key(或 Name)

3) 其余样式需要按照上面的说明放置

4) 在下面的代码中,如果您重新定义了一些其他样式所基于的基本样式,则更改将不会反映,直到您在 MyResources2.xaml 中也重新定义继承的样式(或者将 MyResources.xaml 中的基本样式替换为样式MyResources2.xaml)

<ResourceDictionary.MergedDictionaries>
  <ResourceDictionary Source="MyResources.xaml"/>
  <ResourceDictionary Source="MyResources2.xaml"/>             
</ResourceDictionary.MergedDictionaries> 

5) MergedDictionaries 中的 ResourceDictionaries 用作 LIFO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多