我正在尝试从一个列表框中删除所选项目,并将其添加到新列表框中,如下所示
在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>
删除项目时出现错误&#34;在使用ItemsSource时,操作无效。使用ItemsControl.ItemsSource访问和修改元素。&#34;
答案 0 :(得分:1)
不要通过Items属性操作项目,而是从列表框中绑定的List中添加/删除项目:
<ListBox Name="lstBox1" ItemsSource="{Binding myListProperty}">
...etc...
</ListBox>
如果你的myListProperty
返回一个实现INotifyCollectionChanged的集合(就像ObservableCollection那样),那么列表框会在添加新项目时自动显示这些项目,删除的项目会立即消失。
答案 1 :(得分:1)
我尝试了以下方式并为我工作。
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;