【发布时间】:2013-09-02 02:48:17
【问题描述】:
我的 WPF 应用程序中有一个 ListBox (x:Name = notesList),它从集合中获取 ItemsSource 的项目。该集合是我的班级Data 中的Notes 属性,并且是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 是可能的。
【问题讨论】:
标签: wpf binding listbox two-way-binding