我有两种风格。一种具有隐式键(通过 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' threw an exception.' Line number '14' and line position '19'. ---> System.ArgumentException: Item has already been added. Key in dictionary: 'System.Windows.Controls.Button' Key being added: 'System.Windows.Controls.Button'
这没有任何意义。看起来 x:Key
在 MergedDictionaries
中被忽略。为什么?
最佳答案
看起来这是 XAML 中的一个错误。如果我将 x:Key
移动为第一个属性(在 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>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<Style x:Key="MyButton" TargetType="Button">
</Style>
<Style TargetType="Button">
</Style>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
编辑: bug on Connect
关于wpf - x :Key is ignored inside MergedDictionaries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32491234/