简体   繁体   English

WPF DataGrid - 使用 DataTable 作为 ItemsSource 的自定义排序

[英]WPF DataGrid - Custom Sorting with DataTable as ItemsSource

Using a DataGrid, I display a DataTable with content generated at runtime.使用 DataGrid,我显示了一个包含运行时生成的内容的 DataTable。 I therefore cannot use predefined columns.因此我不能使用预定义的列。 Each row contains a name as its first element and then a variable number of data that are usually numeric but may also be null or the string "Invalid" .每行包含一个名称作为其第一个元素,然后是可变数量的数据,这些数据通常是数字,但也可能是null或字符串"Invalid"

Currently all data is interpreted as strings, which causes the problem that sorting a column results in an alphabetic order, not a numeric one, eg "0, 1, 12, 20, 3" instead of "0, 1, 3, 12, 20".目前,所有数据都被解释为字符串,这会导致按字母顺序而不是数字顺序对列进行排序的问题,例如“0、1、12、20、3”而不是“0、1、3、12, 20"。 I tried to work around this by either inheriting all displayed data from IComparable<T> (which the DataGrid ignores), or by overriding the OnSorting() method of DataGrid (for which I only found sources that assume I am using ListCollectionViews, not DataTables).我试图通过从IComparable<T>继承所有显示的数据(DataGrid 忽略)或覆盖 DataGrid 的OnSorting()方法(我只找到假设我使用的是 ListCollectionViews,而不是 DataTables 的来源)来解决这个问题).

Does anyone know how to implement custom sorting behavior on a DataGrid that is bound to a DataTable generated at runtime?有谁知道如何在绑定到运行时生成的 DataTable 的 DataGrid 上实现自定义排序行为?

I would work with the DataTable instead of tampering with the DataGrid.我会使用 DataTable 而不是篡改 DataGrid。

If can't do anything with the source to the DataTable, you can use a DataView to get a sorted view of the DataTable (see DataView.Sort).如果不能对 DataTable 的源做任何事情,您可以使用 DataView 来获取 DataTable 的排序视图(请参阅 DataView.Sort)。

Bind the DataView to the DataGrid.将 DataView 绑定到 DataGrid。

Add an extra column and use DataColumn.Expression to convert the string values to numeric values and handle the null and Invalid values.添加一个额外的列并使用 DataColumn.Expression 将字符串值转换为数值并处理 null 和无效值。

See the example here:请参阅此处的示例:

https://learn.microsoft.com/en-us/do.net/api/system.data.datacolumn.expression?view.netframework-4.8 https://learn.microsoft.com/en-us/do.net/api/system.data.datacolumn.expression?view.netframework-4.8

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

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