2011-07-21 24 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 />