如何使用 XAML 中的资源初始化只读项集合

Pom*_*oma 5 .net c# wpf xaml

假设我对只读Items集合有一定的控制权。我可以使用集合语法初始化该集合:

<Something>
    <Something.Items>
        <Item />
        <Item />
    </Something.Items>
</Something>
Run Code Online (Sandbox Code Playgroud)

假设现在我有资源集合并希望用它初始化我的控件:

<Window.Resources>
    <ItemCollectionClass x:Key="collection">
        <Item />
        <Item />
    </ItemCollectionClass>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

怎么做?<Something Items="{StaticResource collection}" />不起作用,因为它试图设置集合实例,而不是初始化它。

sel*_*dog 3

您可以使用 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 />
Run Code Online (Sandbox Code Playgroud)