如何从一个列表框中删除项目并添加到另一个列表框中
本文关键字:列表 删除项目 添加 另一个 一个 | 更新日期: 2023-09-27 17:49:27
我试图从一个列表框中删除选定的项目,并将其添加到新的列表框中,如下代码
Binding on 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属性操作项目,而是从列表中添加/删除ListBox绑定的项目:
<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;