Since you populated the list by binding the ObservableCollection using ItemsSource, you cannot change the Items property in the list.
ItemsSource can only be set when the Items collection is empty, and items can only be changed if the ItemSource is NULL.
Otherwise, you will receive the error message "Operation is not valid when using ItemsSource ..."
What you need to do is change the base collection, and since this is an ObservableCollection, the ListBox will reflect the changes.
The following code shows how you can move an item up and down by replacing an item in a collection.
The corresponding XAML simply contains a list called lbItems, and 2 buttons that connect event handlers.
public partial class MainWindow : Window { private ObservableCollection<string> ListItems = new ObservableCollection<string> { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6" }; public MainWindow() { InitializeComponent(); lbItems.ItemsSource = this.ListItems; } private void up_click(object sender, RoutedEventArgs e) { var selectedIndex = this.lbItems.SelectedIndex; if (selectedIndex > 0) { var itemToMoveUp = this.ListItems[selectedIndex]; this.ListItems.RemoveAt(selectedIndex); this.ListItems.Insert(selectedIndex - 1, itemToMoveUp); this.lbItems.SelectedIndex = selectedIndex - 1; } } private void down_click(object sender, RoutedEventArgs e) { var selectedIndex = this.lbItems.SelectedIndex; if (selectedIndex + 1 < this.ListItems.Count) { var itemToMoveDown = this.ListItems[selectedIndex]; this.ListItems.RemoveAt(selectedIndex); this.ListItems.Insert(selectedIndex + 1, itemToMoveDown); this.lbItems.SelectedIndex = selectedIndex + 1; } } }
Peter Hansen
source share