XAML - MergedDictionaries throwing XmlParseException “item has already been added”. Why?

柔情痞子 提交于 2019-12-23 09:36:56

问题


I have the following, very easy to reproduce problem: I'm creating a xaml application which uses resources from another file. The way to go is to create a MergedDictionaries-tag to merge the local and global resources, like this:

<Window>
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="path.to.xaml.file"/>
            <ResourceDictionary>
                <Style TargetType="{x:Type Border}" x:Key="TypeBlock">

                </Style>
                <Style TargetType="{x:Type Border}" x:Key="SetBlock">

                </Style>
            </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>
....
</Window>

This little piece of code will crash if you run it:

Item has already been added. Key in dictionary: 'System.Windows.Controls.Border'  Key being added: 'System.Windows.Controls.Border'

If we remove the MergedDictionaries-tag, the code will run as expected:

<Window>
<Window.Resources>
    <Style TargetType="{x:Type Border}" x:Key="TypeBlock">

    </Style>
    <Style TargetType="{x:Type Border}" x:Key="SetBlock">

    </Style>
</Window.Resources>
</Window>

I don't understand why it throws the exception when we use Merged Resources. Off course, the fix is easy enough for now (move the resources to a lower level). It would be nice to know if this is 'normal' behavior...


回答1:


If your resources are not located in a separate file, then they shouldn't be part of the merged dictionaries. Move them outside like this:

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="path.to.xaml.file"/>
        </ResourceDictionary.MergedDictionaries>

        <Style TargetType="{x:Type Border}" x:Key="TypeBlock">

        </Style>
        <Style TargetType="{x:Type Border}" x:Key="SetBlock">

        </Style>
    </ResourceDictionary>
</Window.Resources>

That said, the error message is a little misleading and may be a result of a bug in the XAML compiler.



来源:https://stackoverflow.com/questions/2040804/xaml-mergeddictionaries-throwing-xmlparseexception-item-has-already-been-adde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!