【问题标题】:DataGridView databinding to List<List<KeyValuePair<string,string>>>DataGridView 数据绑定到 List<List<KeyValuePair<string,string>>>
【发布时间】:2012-07-20 21:52:25
【问题描述】:

我正在尝试将我的 datagridview 的 itemssource 属性绑定到一个对象列表,这些对象的属性名称直到运行时才知道。

代码当前编译,但列中没有显示任何内容(数据网格为我的列表中的每个项目显示一行,但每列中没有任何内容)

设置列绑定

foreach (KeyValuePair<string, string> pair in _columns)
{
    Microsoft.Windows.Controls.DataGridTextColumn textCol = new Microsoft.Windows.Controls.DataGridTextColumn();
    textCol.Header = pair.Key;
    textCol.Binding = new Binding(pair.Value);
    ItemListDataGrid.Columns.Add(textCol);
}

硬编码列表示例:

List<List<KeyValuePair<string,string>>> itemSet = new List<List<KeyValuePair<string,string>>>();
List<KeyValuePair<string,string>> item1 = new List<KeyValuePair<string,string>>();
item1.Add(new KeyValuePair<string,string>("ACTION","ACTION"));
itemSet.Add(item1);
ItemListDataGrid.ItemsSource = itemSet;

任何想法如何让它工作?

【问题讨论】:

  • 你没有给我们任何继续。 “我无法让它工作”是什么意思?它抛出异常?向我们展示例外情况。向我们展示代码。
  • 该列在 datagridview 中显示为空白,如上所述。编辑:添加代码更清晰
  • 为什么不是List&lt;Dictionary&lt;K,V&gt;&gt;
  • 我想将 itemssource 绑定到一组可枚举的对象,直到运行时我才知道键。每个“行”有多个“列”。

标签: c# wpf data-binding wpfdatagrid


【解决方案1】:

我认为你正在尝试做的是实现一个 expando 对象:

http://www.west-wind.com/weblog/posts/2012/Feb/08/Creating-a-dynamic-extensible-C-Expando-Object

也就是说,有关您正在寻找的内容的更多信息将有助于回答您的问题。

【讨论】:

  • 我需要某种方式来表示一个可以用作 DataGridView 的 Itemssource 的对象,而无需提前知道属性名称是什么,或者它们有多少。
  • 是的 - 它被称为 expando 对象,链接向您展示了如何使用动态来做到这一点。
  • 虽然 expando 对象确实解决了我的问题,但我认为它会比我对这个特定问题所需要的更复杂。
【解决方案2】:

使用动态填充的 DataTable,我能够相对快速地解决这个问题。 expando 对象也可以工作,但我只需要将对象加载到 datagridview 中进行选择,之后就不需要它们了。因此,我决定在这种情况下不使用 expando 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    相关资源
    最近更新 更多