如何在Xaml元素中填充多个集合属性
我正在创建一个类,该类继承自如何在Xaml元素中填充多个集合属性,xaml,xamlparseexception,Xaml,Xamlparseexception,我正在创建一个类,该类继承自System.Windows.Documents.paragration,并添加一个新的集合属性。下面是该类的一个非常简化的表示: public class ExtendedParagraph : Paragraph { public Dictionary<string, string> Attributes { get; set; } } 然而,这种方法存在两个问题: [1] 当使用XamlReader解析上述Xaml时,它将失败,并显示消息“
System.Windows.Documents.paragration
,并添加一个新的集合属性。下面是该类的一个非常简化的表示:
public class ExtendedParagraph : Paragraph
{
public Dictionary<string, string> Attributes { get; set; }
}
然而,这种方法存在两个问题:
[1] 当使用XamlReader解析上述Xaml时,它将失败,并显示消息“ExtendedParagation.Inlines属性已设置,只能设置一次”
[2] 我不确定应该使用什么标记来声明Attributes元素中KeyValuePair的实例
我希望有人能给我指出正确的方向
非常感谢,,
提姆
编辑-我已找到问题[1]的答案。它只需要首先声明Attributes集合(使用property元素语法),然后声明段落内容:
<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>
在这里声明Attributes属性的成员
这就是段落内容的所在
然而,向
字典
声明性地添加成员被证明更加困难。我在中发现了一些线索,但我还没有取得工作成果。您的想法仍然受欢迎。我不确定是否可以回答我自己的问题,但是,因为似乎没有其他人知道,我将分享我采用的解决方案
显然,Xaml中对泛型的支持是有限的,这意味着没有原生Xaml机制来填充字典(或任何其他泛型集合类)
但是,如前所述,可以创建自定义标记扩展类,一旦配置为适合集合成员类型,它将以声明方式成功填充集合属性:
<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>
你好
世界
<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>