我正在创建一个继承自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>
被证明更加困难。我在这篇文章中找到了一些线索,但我还没有取得工作成果。您的想法仍然受到欢迎。