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

标签 c# .net wpf xaml

假设我对只读 Items 有一些控制权收藏。我可以使用集合语法初始化这个集合:

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

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

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

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

最佳答案

您可以使用 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 />

关于c# - 如何使用 XAML 中的资源初始化只读项集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6776867/

相关文章:

c# - 使用 C# 更新另一台机器(共享文件夹/网络)上存在的文件(web.config)中的值

c# - 从 ASP.NET 与 SQL Mgmt Admin 调用时存储过程速度较慢

c# - 跨请求保留新声明

c# - 在功能区 UI 中切换选项卡

c# - WPF绑定(bind)(使用触发器)不能从文本框工作到标签

C# 从 xml 属性中获取值

c# - 包含 "AsEnumerable()"等效项的 Linq 查询

c# - SoapExtension System.Configuration.ConfigurationErrorsException in web.config 无法解析属性 'type'的值

.net - WinForm CRUD App 的 UI 设计,有什么作用?

c# - 按下 Windows 修饰键时,Keyboard.Modifiers 为 None