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>
source share