Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Moving/ReOrdering of ListView Header in WPF?

Tags:

listview

wpf

The WPF ListView control allows to re-order of columns by drag and drop. Is there any way to disable it?

I hope some WPF guru can help me. :)

like image 974
Soe Moe Avatar asked Nov 28 '22 10:11

Soe Moe


2 Answers

<ListView.View>
     <GridView AllowsColumnReorder="False">
      ......headers here........
     </GridView>
 </ListView.View>

Try this

like image 176
Arsen Mkrtchyan Avatar answered Dec 06 '22 18:12

Arsen Mkrtchyan


I'm using WPF listView with N number of columns where the 1st column must behave like a margin column and it should remain the 1st all the times

How Can I disable the re-order for 1st column only, and keep other columns "reorder-able"?

I can disable the drag-drop of the 1st column using IsHitTestVisible property which will disable the mouse inputs, but I noticed that user can drag the 2nd column (for example) and drop it right before the 1st column and this will swap the 1st column with the 2nd column?

I figured out how to do it:

1) first subscribe to the event:

GridView gridView = this.dbListView.View as GridView;
gridView.Columns.CollectionChanged += new NotifyCollectionChangedEventHandler(Columns_CollectionChanged);

2) Event handler is:

    /// <summary>
    /// This event is executed when the header of the list view is changed - 
    /// we need to keep the first element in it's position all the time, so whenever user drags any columns and drops
    /// it right before the 1st column, we return it to it's original location
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void Columns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        GridViewColumnCollection collection = (GridViewColumnCollection)sender;
        if (e.Action == NotifyCollectionChangedAction.Move) //re-order event
        {
            if (e.NewStartingIndex == 0) //if any of the columns were dragged rigth before the 1st column
            {
                this.Dispatcher.BeginInvoke((Action)delegate
                {
                    GridView gridView = this.dbListView.View as GridView;
                    //removing the event to ensure the handler will not be called in an infinite loop
                    gridView.Columns.CollectionChanged -= new NotifyCollectionChangedEventHandler(Columns_CollectionChanged);
                    //reverse the re-order move (i.e. rolling back this even)
                    collection.Move(e.NewStartingIndex, e.OldStartingIndex);
                    //re-setup the event to ensure the handler will be called second time
                    gridView.Columns.CollectionChanged += new NotifyCollectionChangedEventHandler(Columns_CollectionChanged);
                });
            }
        }

    }
like image 43
Rida Shamasneh Avatar answered Dec 06 '22 18:12

Rida Shamasneh