2010-04-07 26 views
1

我正在创建一个继承自System.Windows.Documents.Paragraph的类并添加了一个新的集合属性。下面是类的一个非常简化的表示:如何填充Xaml元素中的多个集合属性

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

我需要创建并从内XAML中,这需要一个标记语法,其允许该段的内容和成员填充上述类的实例其属性集合需要单独声明。

由于段落类用属性[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]当上述XAML是使用解析XamlReader,它失败,消息“ExtendedParagraph.Inlines属性已被设置,并且只能设置一次”

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

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

非常感谢, 添

编辑 - 我已经找到了答案质疑[1]。它仅仅需要声明属性集合(使用属性元素语法)第一,其次是该段的内容:

<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> 

然而,声明性地将成员添加到一个Dictionary<TKey, TValue>被证明更加困难。我在this post找到了一些线索,但是我还没有取得一个工作成果。你的想法仍然受欢迎。

回答

2

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

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

然而,随着this article描述,可以创建自定义标记扩展类,一旦设定,以适应集合成员类型,它将成功填充声明集合属性:

<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> 
相关问题