XAML: 属性“Resources”被设置多次

52

我遇到了以下错误:

属性“Resources”被设置了多次。

这是我的XAML:

<UserControl.Resources>
    <!--Resource dictionaries for framework stuff-->
    <ResourceDictionary>
        <Style x:Key="MultiLineTextBox" TargetType="TextBox">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="TextWrapping" Value="WrapWithOverflow"/>
        </Style>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/View;component/Common/ResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>

    <!--Convertors needed for proper display-->
    <c:CollapsedIfNegative x:Key="CollapseIfNegative"/>
    <c:VisibleIfNegative x:Key="MakeVisibleIfNegative"/>
    <c:ErrorCodeToString x:Key="ConvertErrorCodeToString"/>
</UserControl.Resources>
2个回答

102
在Xaml中,.Resources属性是很聪明的,它的类型是ResourceDictionary。但是,如果您没有在其内容周围显式地放置<ResourceDictionary>标记,编译器会自动为您假设一个标记,这就是为什么通常可以将画笔直接放入标记中的原因。
然而,您已经开始自己放置ResourceDictionary,我怀疑这可能会阻止自动行为的发生,因此编译器现在认为您正在尝试设置多个值。如果您按照以下方式重写,则应该获得所需的结果:
<UserControl.Resources>
    <!--Resource dictionaries for framework stuff-->
    <ResourceDictionary>
        <!--Convertors needed for proper display-->
        <!-- move this INSIDE the ResourceDictionary tag -->
        <c:CollapsedIfNegative x:Key="CollapseIfNegative"/>
        <c:VisibleIfNegative x:Key="MakeVisibleIfNegative"/>
        <c:ErrorCodeToString x:Key="ConvertErrorCodeToString"/>


        <Style x:Key="MultiLineTextBox" TargetType="TextBox">
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="TextWrapping" Value="WrapWithOverflow"/>
        </Style>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/View;component/Common/ResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

这个可以工作,但我不明白为什么它会对转换器在<ResourceDictionary>中作为最后一个元素有问题,而不会对它们作为第一个元素有问题。 - Adam S
1
在你的例子中,它们根本不在 ResourceDictionary 中。我认为 MergedDictionaries 元素必须是第一个或最后一个,但除此之外顺序并不重要。 - Dan Puzey
8
这句话价值连城:“如果你没有明确地在内容周围放置一个<ResourceDictionary>标签,编译器会自动假定一个标签”--非常感谢。 - Lynn Crumbling

0
实际上,如果我将你的XAML复制并粘贴到我的自定义用户控件中(假设我添加了引用的转换器类),它就可以正常编译。
你的错误列表里是否还有其他错误呢?有时候,如果出现其他错误(比如无法找到资源),可能会导致另一个编译错误的发生。

错误45:属性元素不能在元素内容的中间。它们必须在内容之前或之后。 - Adam S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接