【问题标题】:how to Remove item from one Listbox and add into another Listbox?如何从一个列表框中删除项目并添加到另一个列表框中?
【发布时间】:2012-12-26 06:39:36
【问题描述】:

我正在尝试从一个列表框中删除所选项目并将其添加到新列表框中,如下代码

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 访问和修改元素。”

【问题讨论】:

  • 好吧,正如错误消息中所说,当您的 ListBoxes 被绑定时,您必须使用 ItemsSource。所以修改你的 dtData 来删除和插入其他东西
  • 看看这个 Stackoverflow 帖子,看看它是否也有助于 GOOGLE 错误消息并将 WPF 放在最后你会得到很多点击 stackoverflow.com/questions/11089104/…

标签: c# wpf windows


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我尝试了以下方式,它对我有用。

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多