我有以下非常容易重现的问题:我正在创建一个使用另一个文件中的资源的 xaml 应用程序。解决方法是创建一个 MergedDictionaries 标签来合并本地和全局资源,如下所示:

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

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

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

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

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

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

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

我不明白为什么当我们使用合并资源时它会抛出异常。当然,目前修复很容易(将资源移至较低级别)。很高兴知道这是否是“正常”行为......

有帮助吗?

解决方案

如果您的资源不位于单独的文件中,那么它们不应该成为合并字典的一部分。像这样将它们移到外面:

<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 编译器中的错误造成的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top