Move Up/Down ListBoxItem in ListBox in WPF

Introduction

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.

image1.gif

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.

image2.gif

Now let's have sample data that we would bind to the ListBox.

image3.gif

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.

image4.gif

Above code display is for displaying the SortableObservableCollection.

Now how to use SortableObservableCollection for Sorting an ObservableCollection, follow below code:

image5.gif

Now we will customize the DataTemplate of the ItemTemplate of the ListBox for better display.

The following XAML for your reference:

image6.gif

Now we will run our application and see the sample data being loaded to the ListBox.

image7.gif

Now we will do Move Up functionality.

Move Up

image8.gif

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.

Move Down

image9.gif

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.

image10.gif

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.

image11.gif

And it's done.

Similarly Move down button would work.

Hope this article helps.

Up Next
    Ebook Download
    View all
    Learn
    View all