XAML - 抛出XmlParseException的MergedDictionaries"项已添加".为什么?

Roe*_*elF 6 wpf xaml styles resourcedictionary

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

<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>
Run Code Online (Sandbox Code Playgroud)

如果运行它,这段代码会崩溃:

Item has already been added. Key in dictionary: 'System.Windows.Controls.Border'  Key being added: 'System.Windows.Controls.Border'
Run Code Online (Sandbox Code Playgroud)

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

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

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

    </Style>
</Window.Resources>
</Window>
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它在我们使用Merged Resources时抛出异常.当然,修复现在很容易(将资源调到较低的水平).很高兴知道这是否是"正常"行为......

Ken*_*art 10

如果您的资源不在单独的文件中,那么它们不应该是合并的字典的一部分.像这样把它们移到外面:

<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>
Run Code Online (Sandbox Code Playgroud)

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