【问题标题】:ListBox Item Removal列表框项删除
【发布时间】:2011-05-21 15:45:13
【问题描述】:

我有一个管理配置集的 WPF 窗口,它允许用户编辑配置集(编辑按钮)和删除配置集(删除按钮)。该窗口有一个 ListBox 控件,该控件按名称列出配置集,并且其 ItemsSource 具有与配置集列表的绑定集。

我正在尝试删除窗口代码隐藏文件中的项目..

private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
    var removedItems = configSetListBox.SelectedItems;

    foreach(ConfigSet removedItem in removedItems)
    {
        configSetListBox.Items.Remove(removedItem);
    }
}

我的代码产生了一个无效的操作异常,指出“改为使用 ItemsControl.ItemsSource 访问和修改元素”。我应该访问什么属性才能从 ListBox 中正确删除项目?或者在 WPF 中是否有更优雅的方式来处理这个问题?如果你愿意的话,我的实现有点像 WinForm :)

解决方案

private void RemoveButton_Click(object sender, RoutedEventArgs e)
{   
    foreach(ConfigSet removedItem in configSetListBox.SelectedItems)
    {
        (configSetListBox.ItemsSource as List<ConfigSet>).Remove(removedItem);
    }
    configSetListBox.Items.Refresh();
}

在我的例子中,我有一个 List 作为 ItemSource 绑定类型,所以我必须以这种方式进行转换。如果不刷新 Items 集合,ListBox 不会更新;所以这是我的解决方案所必需的。

【问题讨论】:

  • 您的 itemsource 是可观察的集合吗?

标签: c# wpf data-binding listbox


【解决方案1】:

使用:

private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
  foreach(ConfigSet item in this.configSetListBox.SelectedItems)
  {
      this.configSetListBox.ItemsSource.Remove(item); // ASSUMING your ItemsSource collection has a Remove() method
  }
}

注意:我使用这个。就是这样,因为它更明确 - 它还有助于我们看到对象在类命名空间中,而不是我们所在方法中的变量 - 尽管在这里很明显。

【讨论】:

    【解决方案2】:

    这是因为,您在迭代集合时正在修改集合。

    如果您绑定了列表框的项目源,请尝试从源中删除项目

    【讨论】:

      【解决方案3】:

      这里已经回答了。

      WPF - Best way to remove an item from the ItemsSource

      您需要实现一个 ObservableCollection,然后您对它所做的任何事情都会反映在您的列表框中。

      【讨论】:

      • Mrk Mnl 显示的代码与链接中的代码相同,只是他正在走整个过程。
      【解决方案4】:

      我使用了这个逻辑。它奏效了。

      可能想试试。

      private void RemoveSelectedButton_Click(object sender, RoutedEventArgs e) {
              if (SelectedSpritesListBox.Items.Count <= 0) return;
      
              ListBoxItem[] temp = new ListBoxItem[SelectedSpritesListBox.SelectedItems.Count];
              SelectedSpritesListBox.SelectedItems.CopyTo(temp, 0);
              for (int i = 0; i < temp.Length; i++) {
                  SelectedSpritesListBox.Items.Remove(temp[i]);
              }
          }
      

      【讨论】:

        【解决方案5】:
        for (int i = lstAttachments.SelectedItems.Count - 1; i >= 0; i--)
        {
           lstAttachments.Items.Remove(lstAttachments.SelectedItems[i]);
        }
        

        从您迭代的列表中删除项目的最简单方法是倒退,因为它不会影响您要移动的项目的索引。

        【讨论】:

        • 请编辑您的答案以解释这如何解决问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-07
        • 2010-11-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多