This is a bit ugly but it will reverse the order of the ListBoxItems in listbox1. You can't do the obvious thing: use a single temp variable and swap two elements per loop iteration. You get a runtime error, "Element already has a logical parent. It must be detached from the old parent before it is attached to a 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's the XAML for a complete 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>