Moving ListBox items (descending order sort by "nothing")

Is it possible to sort items in a WPF ListBox in the reverse order from their original order? I mean, you can use SortDescriptions to sort by some property, but what if I just need to show the elements in reverse without a real field to sort against?

Note. I would prefer not to sort the original collection or clone it, etc. I know how to do this, but I'm looking for a way to make a ListBox do this for presentation only.

thanks

+4
source share
3 answers

A cheap answer would be to add a new integer field to the data object and increase it for each element. Then you can change the sorting in this field. I understand that this may not be an acceptable solution.

If you use the collection view for sorting, I believe that you always need to sort based on some property or state. Sorting will be based on a comparison object that implements IComparer. This interface compares two objects and determines which is larger. You cannot undo the sorting unless you have a way to determine how to arrange the two elements by comparing them.

0
source

This is a little ugly, but it will reorder the ListBoxItems in listbox1. You cannot do the obvious thing: use one temporary variable and swap two elements for an iteration of the loop. You get a runtime error: β€œ The element already has a logical parent. It must be separated from the old parent before joining the new one.

 using System; using System.Windows; using System.Windows.Controls; namespace ReverseListbox { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { ItemCollection items = this.listbox1.Items; for (int i = 0, j = items.Count - 1; i < j; i++, j--) { object tmpi = items[i]; object tmpj = items[j]; items.RemoveAt(j); items.RemoveAt(i); items.Insert(i, tmpj); items.Insert(j, tmpi); } } } } 

Here is the XAML for the full sample:

 <Window x:Class="ReverseListbox.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <ListBox Name="listbox1" Grid.Row="0"> <ListBoxItem Content="1" /> <ListBoxItem Content="2" /> <ListBoxItem Content="3" /> <ListBoxItem Content="4" /> </ListBox> <Button Name="button1" Grid.Row="1" Click="Button_Click" /> </Grid> </Window> 
+1
source

I had a similar problem a while ago. I ended up solving it similarly to Josh G.'s post, but used a bit of encapsulation to avoid polluting the domain object.

See this thread of discussion .

Another method that I use for collections that are only used by the user interface (for example, log messages) is to simply insert them in the reverse order, primarily through collection.Insert(0, item); .

0
source

All Articles