wpf - x :Key is ignored inside MergedDictionaries

标签 wpf xaml

我有两种风格。一种具有隐式键(通过 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:KeyMergedDictionaries 中被忽略。为什么?

最佳答案

看起来这是 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/

相关文章:

c# - WPF:绑定(bind)到目录

wpf - XAML 依赖属性与常规属性

c# - 依赖属性重入(或 : why does this work? )

c# - 获取 ComboBox 绑定(bind)多列列表的选定项

wpf - 在 ListBoxItem.ContentTemplate 中有一个 ContentPresenter 有什么问题吗?

wpf - 我从哪里开始设计包含子对象的自定义控件?

wpf - 绑定(bind)时如何在xaml中进行计算?

wpf - 为什么在这种情况下无法解析 StaticResource?

xaml - UWP/XAML : Larger reveal effect (or gradient customization) on ListView

c# - 如何使用NavigateToPageAction更改 View ?