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.