【发布时间】:2014-03-05 23:23:02
【问题描述】:
您可以在下面看到我是如何尝试通过合并字典来分离样式(为了简洁起见,我跳过了命名空间)
App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Style/Colors.xaml" />
<ResourceDictionary Source="Style/HeaderStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Colors.xaml:
<SolidColorBrush x:Key="DarkTextForeground" Color="#7471b9"/>
HeaderStyle.xaml:
<Style x:Key="HeaderTextBlockStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource DarkTextForeground}"/>
<Setter Property="FontWeight" Value="Black"/>
</Style>
在编译过程中出现以下错误:
找不到名称/键为 DarkTextForeground 的资源
为了让它工作,我们必须像这样在 HeaderStyle.xaml 中合并 Colors.xaml:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Colors.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style x:Key="HeaderTextBlockStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource DarkTextForeground}"/>
<Setter Property="FontWeight" Value="Black"/>
</Style>
谁能给我解释一下,为什么我必须在 HeaderStyle.xaml 中引用 Colors.xaml?
我不能只引用在不同合并中定义的样式吗?字典?
我假设 Colors.xaml 是在 HeaderStyle.xaml 之前加载的,因此以后定义的字典应该可以看到它。
【问题讨论】:
-
您说的是 Visual Studio 设计时间吧?实际的项目会构建/运行正常吗?通过在 App.xaml
Application.Resources中引用 MergedDictionaries,我能够在设计时使其工作 -
@BrockHensley 我有点困惑,因为在 HeaderTyle.xaml 中没有
MergedDictionary的示例中:在 VS 设计视图中一切正常(我可以看到带颜色的文本),我什至可以成功构建项目,但是当我尝试运行它时,我得到 XamlParseException: Cannot find a Resource with the Name/Key DarkTextForeground. -
@Romasz 所说的 +1。正是发生在我身上。
-
静态资源在编译时通过仅查看该 ResourceDictionary 及其 MergedDictionaries 中的任何资源字典来解析。它确实会尝试走到父母面前并检查兄弟词典。我什至认为 RD 没有指向“父”字典的指针。
-
糟糕,我的意思是“它不会尝试向上走”。无论如何,这个问题似乎是答案,但无论如何我都会修改我的评论,以防有人稍后阅读它。
标签: c# wpf xaml windows-phone-7 windows-phone-8