2010-04-07 67 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>