XAML - MergedDictionaries 抛出 XmlParseException“项目已添加".为什么? [英] XAML - MergedDictionaries throwing XmlParseException "item has already been added". Why?

查看:47
本文介绍了XAML - MergedDictionaries 抛出 XmlParseException“项目已添加".为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下很容易重现的问题:我正在创建一个 xaml 应用程序,它使用另一个文件中的资源.要走的路是创建一个 MergedDictionaries-tag 来合并本地和全局资源,如下所示:

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'

如果我们删除 MergedDictionaries-tag,代码将按预期运行:

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

推荐答案

如果您的资源不在单独的文件中,则它们不应成为合并词典的一部分.像这样将它们移到外面:

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>

也就是说,错误消息有点误导,可能是 XAML 编译器中的错误造成的.

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

这篇关于XAML - MergedDictionaries 抛出 XmlParseException“项目已添加".为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆