【发布时间】: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/…