this.datagrid.RowDragDropController.Dropped += RowDragDropController_Dropped;
private void RowDragDropController_Dropped(object sender, GridRowDroppedEventArgs e)
{
if (e.DropPosition != DropPosition.None)
{
//Get Dragging records
ObservableCollection<object> draggingRecords = e.Data.GetData("Records") as ObservableCollection<object>;
//Gets the TargetRecord from the underlying collection using record index of the TargetRecord (e.TargetRecord)
var targetRow = viewModel.GridItemSource.Rows[(int)e.TargetRecord];
////Use Batch update to avoid data operatons in SfDataGrid during records removing and inserting
this.datagrid.BeginInit();
var dataCollection = new List<object>();
////Removes the dragging records from the underlying collection
foreach (DataRowView item in draggingRecords)
{
List<object> rowData = new List<object>();
foreach (var column in item.Row.ItemArray)
rowData.Add(column);
dataCollection.Add(rowData);
viewModel.GridItemSource.Rows.Remove(item.Row);
}
//Find the target record index after removing the records
int targetIndex = viewModel.GridItemSource.Rows.IndexOf(targetRow);
int insertionIndex = e.DropPosition == DropPosition.DropAbove ? targetIndex : targetIndex + 1;
insertionIndex = insertionIndex < 0 ? 0 : insertionIndex;
//Insert dragging records to the target position
for (int i = draggingRecords.Count - 1; i >= 0; i--)
{
var newRow = viewModel.GridItemSource.NewRow();
var rowValues = dataCollection[i] as List<object>;
for (int j = 0; j < rowValues.Count; j++)
newRow[j] = rowValues[j];
viewModel.GridItemSource.Rows.InsertAt(newRow, insertionIndex);
}
this.datagrid.EndInit();
}
}
|
this.datagrid.QueryColumnDragging += Datagrid_QueryColumnDragging;
private void Datagrid_QueryColumnDragging(object sender, QueryColumnDraggingEventArgs e)
{
if(e.Reason == QueryColumnDraggingReason.Dropped)
{
var droppedColumn = viewModel.GridItemSource.Columns[e.From];
droppedColumn.SetOrdinal(e.To);
}
}
|