【问题标题】:TwoWay binding listbox - removing item双向绑定列表框 - 删除项目
【发布时间】: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 绑定,因为我希望同步 notesListNotes 集合。当我尝试以这种方式删除所选项目时会出现问题:

NotesList.Items.RemoveAt( notesList.SelectedIndex );

我收到异常:“使用 ItemsSource 时操作无效。改为使用 ItemsControl.ItemsSource 访问和修改元素”。

我的问题:我必须使用收集功能来删除元素吗? data.Notes.RemoveAt(index) ?有没有办法使用ListBox 类删除项目,这样会导致删除集合中的项目?我认为使用 TwoWay Binding 是可能的。

【问题讨论】:

    标签: wpf binding listbox two-way-binding


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 2019-04-06
      • 1970-01-01
      相关资源
      最近更新 更多