【问题标题】:Binding List<List<String>> to DataGrid将 List<List<String>> 绑定到 DataGrid
【发布时间】:2013-12-07 10:49:59
【问题描述】:

我想知道如何将List&lt;List&lt;String&gt;&gt; 绑定到 WPF 中 DataGrid 的列。假设我有以下代码:

List<List<string>> ugly = new List<List<string>>();
List<string> u0 = new List<string>{"one", "two", "three", "four"};
List<string> u1 = new List<string> { "five", "six", "seven", "eight" };
List<string> u2 = new List<string> { "nine", "ten", "eleven", "twelve" };
ugly.Add(u0);
ugly.Add(u1);
ugly.Add(u2);

如果我将数据网格(称为 dataGrid)的 ItemsSource 设置为 List&lt;string&gt; 之一,则一列将填充适当的数据。例如,dataGrid.ItemsSource = u0 会产生以下结果:

如何使ugly 中的每个List&lt;String&gt; 都有一个列?

【问题讨论】:

  • 创建一个自定义类。
  • 您可能不了解网格的工作原理,数据源列表中的每个项目都应对应于网格中的 1 行。这意味着丑陋中的每个List&lt;string&gt; 将对应1 行,列将对应于每个项目的属性,List&lt;string&gt; 中的唯一属性是CountCapacity。所以看起来你被卡住了。您必须将您的 ugly 转换为您的网格可以使用的东西。
  • 根据您的目的,您有几个选项,例如:stackoverflow.com/questions/16812020/… 其他选项可能是定义一个包含每个列的数据网格的 wrapPanel,并使用它们的事件将它们的垂直滚动条偏移量相互链接。
  • @KingKing 有没有办法让数据网格列属性对应于列表中的索引?澄清一下,如果我仍然想在数据结构中有一个 List ,有没有办法让第一列对应于索引 0 处的列表项,第二列对应于索引 1 处的列表项,等等?我问是因为我不知道会有多少个字符串,所以在数据结构中为每个字符串设置专用属性是不可能的。
  • @masturcheef 恐怕这并不容易,因为项目的数量是动态的,而正如我所说,列对应于 Properties,您必须定义或以某种方式创建为列表中的每个项目动态属性,据我所知,这非常困难,而且可能是不可能的。

标签: c# wpf datagrid


【解决方案1】:

dataGrid 中的Column 对应于基础DataItem 集合中的property。您可以通过使用其中包含三个属性的匿名类型数组来做到这一点。

还要确保 dataGrid AutoGenerateColumns 设置为 true

dg.ItemsSource = new[] { new { First = u0[0], Second = u1[0], Third = u2[0] },
                         new { First = u0[1], Second = u1[1], Third = u2[1] },
                         new { First = u0[2], Second = u1[2], Third = u2[2] },
                         new { First = u0[3], Second = u1[3], Third = u2[3] }};

【讨论】:

    【解决方案2】:

    如果您知道外部集合中有多少项目,那么您可以在显示它们之前将内部 List&lt;string&gt; 集合复制到匿名类型中。 .. 使用您的示例:

    var item = new { Column1 = u0, Column2 = u1, Column3 = u2 };
    YourDataGrid.ItemsSource = item;
    

    您可以在 StackOverflow 上从我对 WPF : Dynamically create a grid with specified x rows and y columns 问题的回答中了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-21
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      • 2011-02-10
      相关资源
      最近更新 更多