Move Up/Down ListBoxItem In ListBox In WPF
In this article we will see how we can move up/down a ListBoxItem in ListBox.
Creating A WPF Project
Fire up Visual Studio 2008, create a WPF Application, and name it as ListBoxMoveUpDown.
In some project, the requirement is like we have move up and down the position of the item in ListBox. So let’s achieve it.
Here’s the idea let’s have a User Request Workflow.
First of all we need a ListBox and two buttons saying Move Up and Move Down.
Now let’s have sample data that we would bind to the ListBox.
The above class is the structure of a Workflow. Instead of Rank you can use the term Priority.
Now we need a SortableObservableCollection that can Sort Ranks based on the changes, we will make.
Above code display is for displaying the SortableObservableCollection.
Now how to use SortableObservableCollection for Sorting an ObservableCollection, follow below code:
Now we will customize the DataTemplate of the ItemTemplate of the ListBox for better display.
The following XAML for your reference:
Now we will run our application and see the sample data being loaded to the ListBox.
Now we will do Move Up functionality.
Here is the explanation what we have done in above code display. First we are checking whether any item is selected in the ListBox and if yes then we are casting the SelectedItem of the ListBox to Workflow(our class type). Then we are again checking if the Rank of the selected Workflow is not equal to 1. If it is not then we would swap the rank with the previous item. And after that we do the sorting of the SortableObservableCollection.
Moving down the ListBoxItem is similar to Move Up implementation. The only changes are:
To check the ListBoxItem as the Last Item we need to take the ListBox.Items.Count property. And we exchange to the next item present in the ListBox.
That’s it, we would run the application to see the functionalities achieved.
As you see in above image, we have Format System is the 4th Workflow step, which is not correct! It should be the 2nd and then System Engineer can Install Software 1 and 2.
So we would move Format System to 2 rank up.
And it’s done.
Similarly Move down button would work.
Hope this article helps.