【发布时间】:2015-10-14 09:01:41
【问题描述】:
我有两种风格。一种带有隐式键(通过TargetType 属性设置),一种带有显式键:
<Application x:Class="WpfTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<ResourceDictionary>
<Style TargetType="Button" x:Key="MyButton">
</Style>
<Style TargetType="Button">
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
一切正常。现在,如果我在MergedDictionaries 中定义了相同的样式,就像这样:
<Application x:Class="WpfTest.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>
<Style TargetType="Button" x:Key="MyButton">
</Style>
<Style TargetType="Button">
</Style>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
我得到一个运行时异常,指出我有重复的键:
System.Windows.Markup.XamlParseException: 'Set property 'System.Windows.ResourceDictionary.DeferrableContent' 引发异常。'行号“14”和行位置“19”。 ---> System.ArgumentException: 项目已添加。在字典中键入:'System.Windows.Controls.Button' 正在添加的键:'System.Windows.Controls.Button'
这没有任何意义。看起来x:Key 在MergedDictionaries 中被忽略了。为什么?
【问题讨论】:
-
您在执行此操作时是否清理并构建了解决方案?你可以试一试
-
您是说您尝试了我的代码(清单 2)并且对您有用吗?
-
将 TargetType 属性设置为 Button 类型而不设置 x:Key 会将 x:Key 隐式设置为 {x:Type Button}。我假设当您为样式添加 targetType 时,它不会检查键。因此您有相同的键。