How to Cancel DataGrid Column Drag effect?
In the WPF DataGrid control, I use CanUserReorder=True to pin the first three columns and allow columns 4-10 to be reordered by dragging, and want to prevent them from being dragged onto the first three columns. Therefore, I handle e.Cancel=true in the DataGrid_ColumnReordering event. However, the e.NewDisplayIndex property does not exist. How should I achieve the desired effect? The code is as follows: private void DataGrid_ColumnReordering(object sender, DataGridColumnReorderingEventArgs e) { int fixedColumnCount = 3; DataGridColumn draggedColumn = e.Column;
// but have no e.NewDisplayIndex !!!
if (draggedColumn.CanUserReorder && e.NewDisplayIndex < fixedColumnCount)
{
e.Cancel = true;
}
}
Well, the thing is that ColumnReordering is raised at the very start of the event chain (the first is ColumnHeaderDragStarted), so it realistically cannot have such information (because the draggint hasn't finished nor actually progressed), as when you Cancel here, you don't start the drag at all.
If you do start it (without setting Cancel = true), you will continuously receive ColumnHeaderDragDelta giving you the current position; once mouse is released you will receive ColumnHeaderDragCompleted with the final position (and with the last chance to Cancel) and finally ColumnReordered after the columns have been actually reordered.
So to do what you require, which is to prevent other columns being dragged over the first three, you will have to get position of the last "fixed" one within the DataGrid and make sure that the new one wasn't dragged there, accounting for the index in general, realizing your cancel/non-cancel logic within the ColumnHeaderDragCompleted event to return true/false.
I haven't tried this, but couldn't you handle DragOver or similar on the fixed columns and disallow the operation?