我的WPF应用程序中有一个ListBox
(x:Name = notesList
),它从集合中获取ItemsSource
项。该集合是我的班级Notes
中的Data
属性,属于ObservableCollection<Note>
类型。我以这种方式绑定它:(data
是一个Data
对象,其中包含Notes
中的一些项目
Binding bind = new Binding();
bind.Mode = BindingMode.TwoWay;
bind.Source = data;
bind.Path = new PropertyPath("Notes");
notesList.SetBinding(ListBox.ItemsSourceProperty, bind);
绑定工作,项目显示在ListBox中。我设置了TwoWay绑定,因为我希望同步notesList
和Notes
集合。当我尝试以这种方式删除所选项目时会出现问题:
NotesList.Items.RemoveAt( notesList.SelectedIndex );
我得到异常:“在使用ItemsSource时操作无效。使用ItemsControl.ItemsSource访问和修改元素”。
我的问题:我是否必须使用集合功能来删除元素? data.Notes.RemoveAt(index)
?有没有办法使用ListBox
类删除项目,这样会导致删除集合中的项目?我认为使用TwoWay Binding它是可能的。
答案 0 :(得分:1)
所有错误意味着当您使用ItemsSource
属性将集合绑定到集合控件时,您无法从该控件中删除项目。不过不用担心,有一个真正的简单解决方案。而是从集合中删除项目:
data.Notes.Remove(data.Notes.Where(n => n == notesList[notesList.SelectedIndex]).
FirstOrDefault());
最好不要在代码中使用控件...如果将属性绑定到ComboBox.SelectedItem
属性,那么你可以简单地执行此操作:
public Note SelectedNote { get; set; } // should implement INotifyPropertyChanged
......然后......
data.Notes.Remove(SelectedNote);