我无法让 Stephen Lautier 的解决方案在 VB.Net 中工作,但我找到了另一个可以工作的解决方案。
每当发生排序操作时,都会按列出的顺序发生以下事件:
- 排序
- UnloadingRow(适用于 DataGrid 中的所有行)
- LoadingRow(适用于 DataGrid 中的所有行)
- 布局已更新
这可以通过以下方式使用:
变量
Private _updateSorted As Boolean
Private _tempSender As Object
Private _rowsLoaded As List(Of DataGridRowEventArgs)
_rowsLoaded = New List(Of DataGridRowEventArgs)
排序
Private Sub myDataGrid_Sorting(sender As Object, e As DataGridSortingEventArgs) Handles myDataGrid.Sorting
_updateSorted = True
_rowsLoaded.Clear()
_tempSender = Nothing
End Sub
UnloadingRow/Loading Row 事件
'Save pre-sorting state here, if desired'
'Perform operation on pre-sorting rows here, if desired'
Private Sub myDataGrid_UnloadingRow(sender As Object, e As DataGridRowEventArgs) Handles myDataGrid.UnloadingRow
End Sub
'Save post-sorting state here.'
'Perform operation on post-sorting rows here'
'In this example, the operation is dependent on the DataGrid updating its layout first so I included items relevant to handling that'
Private Sub myDataGrid_LoadingRow(sender As Object, e As DataGridRowEventArgs) Handles myDataGrid.LoadingRow
Dim myDataGridCell As DataGridCell = GetCellByRowColumnIndex(myDataGrid, e.Row.GetIndex, colIndex)
'Or whatever layout-dependent object you are using, perhaps utilizing e As DataGridRowEventArgs'
If Not IsNothing(myDataGridCell) Then
'~~ Perform operations here ~~'
Else
If _updateSorted Then
'Update has occurred but the updated DataGrid is not yet available'
'Save variables to use once the DataGrid is updated'
_rowsLoaded.Add(e)
_tempSender = sender
End If
End If
End Sub
布局更新
Private Sub myDataGrid_LayoutUpdated(sender As Object, e As EventArgs) Handles myDataGrid.LayoutUpdated
If _updateSorted Then
Dim rowsLoaded As New List(Of DataGridRowEventArgs)
For Each eRow As DataGridRowEventArgs In _rowsLoaded
rowsLoaded.Add(eRow)
Next
For Each eRow As DataGridRowEventArgs In rowsLoaded
'Now perform the action to the sorted DataGridRows in the order they were added'
myDataGrid_LoadingRow(_tempSender, eRow)
Next
_updateSorted = False
End If
End Sub