1

我正在创建一个继承自System.Windows.Documents.Paragraph并添加新集合属性的类。这是该类的非常简化的表示:

public class ExtendedParagraph : Paragraph
{
    public Dictionary<string, string> Attributes { get; set; }
}

我需要在 Xaml 中创建和填充上述类的一个实例,这需要一种标记语法,允许单独声明段落的内容及其 Attributes 集合的成员。

由于 Paragraph 类是用 attribute 装饰的[ContentProperty("Inlines")],我假设我需要显式地填充 Inlines 和 Attributes 集合。基于我在其他地方看到的用于解决类似挑战的 Xaml 语法,我设想这样的事情:

<ExtendedParagraph xmlns="clr-namespace:MyNamespace">
    <ExtendedParagraph.Inlines>

        This is where the paragraph content goes

    </ExtendedParagraph.Inlines>
    <ExtendedParagraph.Attributes>

        This is where the members of the Attributes property are declared 

    </ExtendedParagraph.Attributes>
</ExtendedParagraph>

但是,这种方法存在两个问题:

[1] 使用 XamlReader 解析上述 Xaml 时,失败并显示消息“ExtendedParagraph.Inlines 属性已设置且只能设置一次”

[2] 我不确定应该使用什么标记在 Attributes 元素中声明 KeyValuePair 的实例。

我希望有人能指出我正确的方向。

非常感谢,蒂姆

编辑 - 我找到了问题 [1] 的答案。它只需要首先声明 Attributes 集合(使用属性元素语法),然后是段落的内容:

<ExtendedParagraph xmlns="clr-namespace:MyNamespace">
    <ExtendedParagraph.Attributes>

        This is where the members of the Attributes property are declared 

    </ExtendedParagraph.Attributes>
    This is where the paragraph content goes
</ExtendedParagraph>

然而,以声明方式将成员添加到 aDictionary<TKey, TValue>被证明更加困难。我在这篇文章中找到了一些线索,但我还没有取得工作成果。您的想法仍然受到欢迎。

4

1 回答 1

2

我不确定是否可以回答我自己的问题,但由于似乎没有其他人知道,我将分享我采用的解决方案。

显然,在 Xaml 中对泛型的支持是有限的,这意味着没有原生的 Xaml 机制来填充Dictionary<TKey, TValue>(或任何其他泛型集合类)。

但是,正如本文所述,可以创建自定义标记扩展类,并且一旦配置为适合集合成员类型,它将以声明方式成功填充集合属性:

<ExtendedParagraph.Attributes>
    <generic:DictionaryOfT TypeArgument="sys:String">
        <generic:DictionaryOfT.Items>
            <sys:String x:Key="String1">Hello</sys:String>
            <sys:String x:Key="String2">World</sys:String>
        </generic:DictionaryOfT.Items>
    </generic:DictionaryOfT>
</ExtendedParagraph.Attributes>
于 2010-04-08T14:37:47.880 回答