【问题标题】:Cannot add element with the same key to resource dictionary - it already exists无法将具有相同键的元素添加到资源字典 - 它已经存在
【发布时间】:2023-09-05 13:09:01
【问题描述】:

解析一个 xaml 文件时出现异常:

结果消息:
测试方法 ThemeResourceDictionaryTest.ParseXaml 抛出异常: System.Windows.Markup.XamlParseException:'向'System.Windows.ResourceDictionary'类型的字典添加值引发异常。'行号“1397”和行位置“4”。 ---> System.ArgumentException:项目已被添加。在字典中键入:'System.Windows.Controls.TextBox' 正在添加的键:'System.Windows.Controls.TextBox'

和我的元素:

<Style x:Key="MyVeryUniqueKey" BasedOn="{StaticResource TextBoxStyle}" TargetType="TextBox">
    <Setter Property="MinWidth" Value="90"/>
</Style>

为什么元素的key设置为TextBox,而我显式设置key为唯一的MyVeryUniqueKey时。

我还有其他样式,其目标类型是 TextBox,但它们都有不同的键。

【问题讨论】:

    标签: c# wpf xaml resourcedictionary


    【解决方案1】:

    我怀疑,在特定的资源字典范围内,您有多个TextBox 样式,其中设置了TargetType,但未设置x:Key

    如果您没有为TextBox 样式显式设置字典键,它将默认为{x:Type TextBox}。显然,您不能将其中两个重复作为字典中的键。

    例如,如果你把这种东西放在资源中:

    <Window.Resources>
        <Style TargetType="{x:Type TextBox}" />
        <Style TargetType="{x:Type TextBox}" />
    </Window.Resources>
    

    然后你会得到一个运行时XamlParseException

    项目已添加。 输入字典:'System.Windows.Controls.TextBox' 正在添加的键:'System.Windows.Controls.TextBox'"

    【讨论】:

      【解决方案2】:

      我在使用不同键的两种样式时遇到了同样的错误。

      x:Key 必须在 TargetType 的前面。我还是不敢相信……

      作品:

      <Style x:Key="ButtonStyle" TargetType="{x:Type Button}"> ...
      <Style x:Key="ButtonStyle2" TargetType="{x:Type Button}"> ...
      

      不起作用:

      <Style TargetType="{x:Type Button}" x:Key="ButtonStyle"> ...
      <Style TargetType="{x:Type Button}" x:Key="ButtonStyle2"> ...
      

      【讨论】:

      • 不确定谁对你投了反对票,但这为我解决了这个问题。我也不敢相信。很奇怪,这里的属性会依赖于位置,但果然,我将 x:Key 移动到 TargetType 之前,然后我就不再收到错误了。
      最近更新 更多