Block column reorder to specific target display index in data grid xaml

55 Views Asked by At

I have an XAML DataGrid which has 10 columns. I am able to reorder the column but I want to block reordering columns within group.

For example, a user can reorder the column no 9 to column no 5 (which is possible now) but column no 9 should not allow to drag less than column no 4.

I want to restrict the column reordering based on display index.

I've tried to use ColumnReordering event but wasn't able to find drop location index of drag column so I can block it.

xaml.cs file

grid.ColumnReordering += Grid_ColumnReordering;

private void Grid_ColumnReordering(object sender, DataGridColumnReorderingEventArgs e) 
{ 
    object DropLocationIndicator = e.DropLocationIndicator; 
    object Dragindicator = e.DragIndicator; 
    // Drag column
     var column = e.Column;

     //find target display index and block it
     if (targetdisplayindex > 4)
     {
         e.Cancel = false;
     }
     else
     {
        e.Cancel = true;
     }
}
1

There are 1 best solutions below

0
On

The ColumnReordering event is raised before the target display index is known. You could use it to store the original column index and then handle the ColumnDisplayIndexChanged to move the column back based on your logic. Something like this:

private int _displayIndex;

private void OnColumnReordering(object sender, DataGridColumnReorderingEventArgs e)
{
    _displayIndex = e.Column.DisplayIndex;
}

private void OnColumnDisplayIndexChanged(object sender, DataGridColumnEventArgs e)
{
    DataGrid dataGrid = (DataGrid)sender;
    int newIndex = e.Column.DisplayIndex;
    int oldIndex = _displayIndex;

    // if (some condition...)
    // switch back:
    dataGrid.ColumnDisplayIndexChanged -= OnColumnDisplayIndexChanged;
    e.Column.DisplayIndex = oldIndex;
    dataGrid.ColumnDisplayIndexChanged += OnColumnDisplayIndexChanged;
}