.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> WPF >> Post New Resource Bookmark and Share   

 Subscribe to Articles

WPF Move Up/Down ListBoxItem in ListBox

Posted By:Diptimaya Patra       Posted Date: April 30, 2010    Points: 25    Category: WPF    URL: http://www.dotnetspark.com  

WPF Move Up/Down ListBoxItem in ListBox. In this article we will see how we can move up/down a ListBoxItem in ListBox.
 

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.

#region Workflow
public class Workflow
{
    public int Rank { get; set; }
    public string Name { get; set; }
    public string AssignedTo { get; set; }
}
#endregion


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.

SortableObservableCollection sortedData;

#region Constructor
public Window1()
{
    InitializeComponent();
    ObservableCollection workflowData = new ObservableCollection 
    {
        new Workflow{Rank=1, Name="Manager Approval", AssignedTo="Manager"},
        new Workflow{Rank=2, Name="Install Software 1", AssignedTo="System Engineer"},
        new Workflow{Rank=3, Name="Install Software 2", AssignedTo="System Engineer"},
        new Workflow{Rank=4, Name="Format System", AssignedTo="System Engineer"},
        new Workflow{Rank=5, Name="Software Approval", AssignedTo="Software Management"},
        new Workflow{Rank=6, Name="Admin Rights Approval", AssignedTo="Manager"},
        new Workflow{Rank=7, Name="Assign as Admin", AssignedTo="System Engineer"},
        new Workflow{Rank=8, Name="Give Feedback", AssignedTo="User"},
    };

    sortedData = new SortableObservableCollection(workflowData);
    sortedData.Sort(x => x.Rank, ListSortDirection.Ascending);

    lbData.ItemsSource = sortedData;
} 
#endregion


Above code display is for displaying the SortableObservableCollection.

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

#region Sortable Observable Collection (Asc/Desc)
public class SortableObservableCollection : ObservableCollection
{
    public SortableObservableCollection(List list)
        : base(list) { }

    public SortableObservableCollection(IEnumerable collection)
        : base(collection) { }

    public void Sort(Func keySelector, ListSortDirection direction)
    {
        switch (direction)
        {
            case ListSortDirection.Ascending:
                {
                    ApplySort(Items.OrderBy(keySelector));
                    break;
                }
            case ListSortDirection.Descending:
                {
                    ApplySort(Items.OrderByDescending(keySelector));
                    break;
                }
        }
    }

    public void Sort(Func keySelector, IComparer comparer)
    {
        ApplySort(Items.OrderBy(keySelector, comparer));
    }

    private void ApplySort(IEnumerable sortedItems)
    {
        var sortedItemsList = sortedItems.ToList();
        foreach (var item in sortedItemsList)
        {
            Move(IndexOf(item), sortedItemsList.IndexOf(item));
        }
    }
}
#endregion


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

The following XAML for your reference:

ListBox x:Name="lbData" Margin="0,0,0,39" Background="Beige">
  
    
      
        
          
          
        
        
        
          
          
        
      
    
  
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

#region Move Up
private void Move_Up(object sender, RoutedEventArgs e)
{
    if (lbData.SelectedIndex != -1)
    {
        Workflow wf = lbData.SelectedItem as Workflow;
        if (wf.Rank != 1)
        {
            MoveUp(wf);
            lbData.ItemsSource = null;
            sortedData.Sort(x => x.Rank, ListSortDirection.Ascending);
            lbData.ItemsSource = sortedData;
        }
    }
}

private void MoveUp(Workflow wf)
{
    foreach (Workflow item in lbData.Items)
    {
        if (item.Rank == wf.Rank - 1)
        {
            item.Rank = wf.Rank;
            break;
        }
    }
    wf.Rank--;
}
#endregion

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
#region Move Down
private void Move_Down(object sender, RoutedEventArgs e)
{
    if (lbData.SelectedIndex != -1)
    {
        Workflow wf = lbData.SelectedItem as Workflow;
        if (wf.Rank != lbData.Items.Count)
        {
            MoveDown(wf);
            lbData.ItemsSource = null;
            sortedData.Sort(x => x.Rank, ListSortDirection.Ascending);
            lbData.ItemsSource = sortedData;
        }
    }
}

private void MoveDown(Workflow wf)
{
    foreach (Workflow item in lbData.Items)
    {
        if (item.Rank == wf.Rank + 1)
        {
            item.Rank = wf.Rank;
            break;
        }
    }
    wf.Rank++;
}
#endregion

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.

You can download the sample project used in the above example.

Hope this article helps.


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend