我有一个包含字母数字的DataGrid,例如:
- 1 second
- 100 mile
- 1499
- 28th street
- 50 apples
- 701: a prime number
- 9
- A banana
由于所有的值都是字符串,所以它按照字符串自动排序。我该如何使其像整数一样排序,如下所示:
- 1 second
- 9
- 28th street
- 50 apples
- 100 mile
- 701: a prime number
- 1499
- A banana
我尝试使用 SortMemberPath
,但不确定如何在代码中实现。
<DataGrid.Columns>
<DataGridTextColumn x:Name="IdColumn" Binding="{Binding Id}" Header="Id"/>
<DataGridTextColumn x:Name="NameColumn" Binding="{Binding Name}" Header="Name" SortMemberPath="NumSort"/>
</DataGrid.Columns>
我甚至尝试实现类似这样的东西,但我想排序的属性在自动生成的代码(ItemsDataSet.Designer.vb)中有超过10000行。不确定在那里放置任何内容是否明智,但无论如何,我已经尝试了以下方式:
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Name() As String
Get
Return CType(Me(Me.tablet_Items.NameColumn),String)
End Get
Set
Me(Me.tablet_Items.NameColumn) = Value
If Value IsNot Nothing Then NumSort = Integer.Parse(Value.ToString())
End Set
End Property
然而,VS报错NumSort
未声明。我不确定在代码中该在哪里声明它,我已经尝试了几个地方,但没有成功。
编辑:
我向前迈出了一小步。我实现了这段代码,可以让我按两列排序,但我仍然不确定如何访问网格中的每条记录以进行比较。
Private Sub dataGridName_Sorting(sender As Object, e As DataGridSortingEventArgs) Handles T_MoviesDataGrid.Sorting
e.Handled = True
Dim cView = CollectionViewSource.GetDefaultView(sender.ItemsSource)
Dim direction As ListSortDirection = ListSortDirection.Ascending
If cView.SortDescriptions.FirstOrDefault().PropertyName = e.Column.SortMemberPath Then
direction = If(cView.SortDescriptions.FirstOrDefault().Direction = ListSortDirection.Descending, ListSortDirection.Ascending, ListSortDirection.Descending)
End If
cView.SortDescriptions.Clear()
If e.Column.SortMemberPath = "NameSort" Then
AddSortColumn(DirectCast(sender, DataGrid), "Name", direction)
AddSortColumn(DirectCast(sender, DataGrid), "Id", direction)
End If
End Sub
Private Sub AddSortColumn(sender As DataGrid, sortColumn As String, direction As ListSortDirection)
Dim cView = CollectionViewSource.GetDefaultView(sender.ItemsSource)
cView.SortDescriptions.Add(New SortDescription(sortColumn, direction))
For Each col In sender.Columns.Where(Function(x) x.SortMemberPath = sortColumn)
col.SortDirection = direction
Next
End Sub
在类似的主题中,人们经常建议使用IComparer。我尝试过实现它,但不确定如何完成。这就是我卡住的地方:
Public Class MyComparing
Inherits MyDataSet
Implements IComparable
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Return '???
End Function
End Class
我尝试使用partial
而不是从MyDataSet继承,但仍然卡住了。
ListCollectionView
,而我有一个不支持CustomSorters的BindingListCollectionView
。 - undefined