torvin
torvin

Reputation: 7091

x:Key is ignored inside MergedDictionaries

I have two styles. One with implicit key (set via TargetType property), and one with explicit key:

<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>

Everything works is expected. Now, If I have the same styles defined inside MergedDictionaries, like that:

<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>

I get a runtime exception, stating that I have duplicate keys:

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'

That makes no sense. Looks like x:Key is being ignored inside MergedDictionaries. Why?

Upvotes: 2

Views: 379

Answers (1)

torvin
torvin

Reputation: 7091

Looks like this is a bug in XAML. If I move x:Key to be the first attribute (before TargetType), then suddenly everything just works.

<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>

Edit: bug on Connect

Upvotes: 4

Related Questions