[英]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.