0
votes

I have a ListBox (x:Name = notesList) in my WPF application which takes items by ItemsSource from collection. The collection is a Notes property in my class Data and is of type ObservableCollection<Note>. I bind it this way: (data is a Data object that have some items in Notes)

Binding bind = new Binding();
bind.Mode = BindingMode.TwoWay;
bind.Source = data;
bind.Path = new PropertyPath("Notes");
notesList.SetBinding(ListBox.ItemsSourceProperty, bind);

The binding works, items are shown in ListBox. I set TwoWay binding, because I want the notesList and Notes collection to be synchronized. The problem occurs when I try to remove selected item this way:

NotesList.Items.RemoveAt( notesList.SelectedIndex );

I get exception: "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead".

My question: Do I have to use collection function to remove element? data.Notes.RemoveAt(index) ? Is there any way to remove item using ListBox class so it will result removing item in collection? I thought that using TwoWay Binding it will be possible.

1

1 Answers

1
votes

All that error means is that when you have used the ItemsSource property to bind a collection to a collection control, you can't remove items from that control. Don't worry though, there's a really simple solution. Remove the item from the collection instead:

data.Notes.Remove(data.Notes.Where(n => n == notesList[notesList.SelectedIndex]).
FirstOrDefault());

It's better to not use the control in your code behind... if you bind a property to the ComboBox.SelectedItem property, then you can simply do this:

public Note SelectedNote { get; set; } // should implement INotifyPropertyChanged

... then...

data.Notes.Remove(SelectedNote);