0

次のコードのように、選択したアイテムを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を使用して要素にアクセスして変更してください。」

4

2 に答える 2

1

Itemsプロパティを介してアイテムを操作するのではなく、ListBoxがバインドされているリストからアイテムを追加/削除します。

<ListBox Name="lstBox1" ItemsSource="{Binding myListProperty}">
  ...etc...
</ListBox>

INotifyCollectionChangedmyListPropertyを実装するコレクションを返す場合(ObservableCollectionのように)、リストボックスには、新しいアイテムが追加されると自動的に表示され、削除されたアイテムはすぐに消えます。

于 2012-12-26T06:59:03.590 に答える
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;
于 2013-01-04T12:23:42.150 に答える