3

我在 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 文件中添加资源。

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

4

2 回答 2

1

其实想通了。

我试图让它在没有密钥的情况下工作,并发现我留在 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

于 2012-04-03T20:54:04.890 回答
1

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

<Application.Resources>
    <ResourceDictionary x:Key="keyname">
       <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="MyResources.xaml"/>
       </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
于 2012-04-03T10:28:11.983 回答