2011-07-21 23 views
3

假設我對只讀Items集合有一些控制。如何使用XAML中的資源初始化只讀項目集合

<Something> 
    <Something.Items> 
     <Item /> 
     <Item /> 
    </Something.Items> 
</Something> 

現在假設我有收集資源,並想用它初始化我的控制:

<Window.Resources> 
    <ItemCollectionClass x:Key="collection"> 
     <Item /> 
     <Item /> 
    </ItemCollectionClass> 
</Window.Resources> 

如何做到這一點,我可以使用集合的語法初始化這個集合? <Something Items="{StaticResource collection}" />不起作用,因爲它試圖設置集合實例,而不是初始化它。

+1

不知道這是可能的,在大多數情況下,你只需使用一個'ItemsSource'屬性用於此。 –

+0

使用新的'ItemsSource'依賴項屬性創建了繼承類。應用程序的作品,但由於某種原因設計師顯示空集合 – Poma

+0

我不明白問題在哪裏。當你將某些東西聲明爲資源時,它就像一個靜態對象。它在加載資源字典時被初始化。那麼,有什麼意義? –

回答

2

您可以用ObjectDataProvider的初始化集合:

<Window.Resources> 
    <ItemCollectionClass x:Key="collection"> 
    <Item /> 
    <Item /> 
    </ItemCollectionClass> 

    <ObjectDataProvider x:Key="..." ObjectType="{x:Type local:Something}"> 
    <ObjectDataProvider.ConstructorParameters> 
     <StaticResource ResourceKey="collection" /> 
    </ObjectDataProvider.ConstructorParameters> 
    </ObjectDataProvider> 
</Window.Resources />