简体   繁体   English

如何使用List(Of T)作为WPF DataGrid的Itemssource?

[英]How to use a List(Of T) as Itemssource for a WPF DataGrid?

I wanted to quickly display a List(OF String) in a DataGrid (dynamically), so I thought 我想快速在DataGrid中显示一个List(OF String)(动态),所以我想

myDataGrid.ItemsSource = myList

would be the quick and easy way to do it, since this works great for a DataTable: 这将是一种快速简便的方法,因为它适用于DataTable:

myDataGrid.ItemsSource = myDataTable.DefaultView

My DataGrid has the AutoGenerateColumns property set to 'True'. 我的DataGrid将AutoGenerateColumns属性设置为“True”。 And for the datatable this works fine, but when I assign the List(Of String) to the ItemsSource, my column name shows up as 'Length' and the displayed data are integers that are the number of characters in each String item in the List, not the actual String item. 对于数据表,这可以正常工作,但是当我将List(Of String)分配给ItemsSource时,我的列名称显示为'Length',显示的数据是整数,它们是List中每个String项中的字符数,而不是实际的String项。

What am I doing wrong? 我究竟做错了什么?

EDIT 编辑

My test list is created like this: 我的测试列表是这样创建的:

Dim myList As New List(Of String)
  For i As Int32 = 1 To 25
  myList.Add("Item #" & i)
Next

The following 2 methods produce the exact same results. 以下两种方法产生完全相同的结果。

Create a CollectionView: 创建一个CollectionView:

Dim cv = CType(CollectionViewSource.GetDefaultView(myList), CollectionView)
DataGrid1.ItemsSource = cv

Just use the List: 只需使用List:

DataGrid1.ItemsSource = myList

Both of these methods display a single column in the DataGrid. 这两种方法都在DataGrid中显示单个列。 The column is titled 'Length' and contains integers matching the length of each string entry. 该列标题为“长度”,包含与每个字符串条目的长度匹配的整数。

EDIT 编辑

Translation of answer by 'testalino' to VB: 'testalino'对VB的回答:

DataGrid1.ItemsSource = myList.Select(Function(s) New With {.Value = s}).ToList

Your case is actually funny. 你的情况实际上很有趣。 You are binding elements of type string to a grid. 您将字符串类型的绑定元素绑定到网格。 The grid then looks for properties in type String that it can display. 然后,网格会查找可以显示的String类型的属性。 the only property found is Length, so it creates a column named Length and displays its value. 找到的唯一属性是Length,因此它会创建一个名为Length的列并显示其值。

What you need to do to avoid this is create a wrapper class for string. 为避免这种情况,您需要做的是为字符串创建一个包装类。

Either create a class explicitly: 要么明确地创建一个类:

class StringWrapper
{
     string Value { get; set;}
}

or by using LINQ: 或者使用LINQ:

List<string> strings = new List<string>();
strings.Add("abc");
strings.Add("def");
dataGrid.ItemsSource = strings.Select(s => new { Value = s }).ToList();

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM