次のコードのように、選択したアイテムを1つのリストボックスから削除し、それを新しいリストボックスに追加しようとしています。
PageLoadでのバインド:
データベースからDataTableにレコードを取得し、それをリストボックスにバインドします。
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を使用して要素にアクセスして変更してください。」