繁体   English   中英

如何从一个列表框中删除项目并添加到另一个列表框?

[英]how to Remove item from one Listbox and add into another Listbox?

我试图从一个列表框中删除所选项目,并将其添加到新列表框中,如下所示

在PageLoad上绑定:

将数据库中的记录导入DataTable并将其绑定到Listbox。

lstBox1.DataContext = dtData;

代码绑定:

  List<object> _selecteditems = new List<object>();
  foreach (var item in lstBox1.SelectedItems)
  {
      _selecteditems.Add(item);
  }
  foreach (var item in _selecteditems)
  {
      lstBox1.Items.Remove(item);
      lstBox2.Items.Add(item);
  }

设计:

<ListBox Name="lstBox1" ItemsSource="{Binding}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding ID}"/>
    </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

<ListBox Name="lstBox2" ItemsSource="{Binding}" >
  <ListBox.ItemTemplate>
     <DataTemplate>
        <TextBlock Text="{Binding ID}"/>
      </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

我在删除项目时遇到错误“当ItemsSource正在使用时操作无效。请改为使用ItemsControl.ItemsSource访问和修改元素。”

不要通过Items属性操作项目,而是从列表框中绑定的List中添加/删除项目:

<ListBox Name="lstBox1" ItemsSource="{Binding myListProperty}">
  ...etc...
</ListBox>

如果你的myListProperty返回一个实现INotifyCollectionChanged的集合(就像ObservableCollection那样),那么列表框会在添加新项目时自动显示新项目,删除的项目会立即消失。

我尝试了以下方式并为我工作。

List<object> _selecteditems = new List<object>();
foreach (var item in lstBox1.SelectedItems)
{
    _selecteditems.Add(item);
}
foreach (var item in _selecteditems)
{
  DataRow dr = dtSelctedDest.NewRow();
  dr[0] = ((DataRowView)item).Row[0].ToString();
  dr[1] = ((DataRowView)item).Row[1].ToString();
  dtSelctedItem.Rows.Add(dr);
  dtAllItem.Rows.Remove(dtAllItem.Rows.Remove.Select(string.Format("ID='{0}'", ((DataRowView)item).Row[0].ToString()))[0]);
 }
 lstBox1.DataContext = dtAllItem;
 lstBox2.DataContext = dtSelctedItem;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM