Move Item from bound Listbox to another bound Listbox

Dec 13 2012 7:09 PM

Hello
I've created two lisboxes. One is bound to an ObservableCollection returning results from SQLight query. The code I have in place works great if listbox2 is not bound.

Basic senario is Listbox1 presents selectable items to populate listbox2. User dblClick listbox1 item and it moves to listbox2. Listbox2 is saved to DB... when the user opens the UI at any given time or even in same session, they should be able to remove items from lisbox2. NOTE (Listbox1 is filtered by whatever is in Listbox2 i.e no items can exist in two listboxes at any given time.)

Problem: As soon as I try and bind listbox2 I get error "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead."

Code:
Listbox1 MouseDoubleClick -
ListBoxItem myListBoxItem =
  (ListBoxItem)(listBoxCertificateLookup.ItemContainerGenerator.ContainerFromItem(listBoxCertificateLookup.Items.CurrentItem));
  // listBoxCertificateSelected.DataContext = null;
  listBoxCertificateSelected.Items.Add(myListBoxItem);

Listbox2 MouseDoubleClick -
ListBoxItem myListBoxItem =
  (ListBoxItem)(listBoxCertificateSelected.ItemContainerGenerator.ContainerFromItem(listBoxCertificateSelected.Items.CurrentItem));
 //listBoxCertificateLookup.DataContext = null;
  listBoxCertificateLookup.Items.Add(myListBoxItem);


Listbox1 -
 ObservableCollection<CertificateLookup> CertificateLookupList = new ObservableCollection<CertificateLookup>();
  foreach (DataRow r in conditions.Rows)
  {
  CertificateLookupList.Add(new CertificateLookup()
  {
  Section = r["Section"].ToString(),
  Description = r["Description"].ToString(),
  SortOrder = r["SortOrder"].ToString()
  });
  listBoxCertificateLookup.DataContext = CertificateLookupList;
  }

Listbox2 -
ObservableCollection<CertificateSelected> CertificateSelectedList = new ObservableCollection<CertificateSelected>();
  foreach (DataRow r in conditions.Rows)
  {
  CertificateSelectedList.Add(new CertificateSelected()
  {
  selectedSection = r["Section"].ToString(),
  selectedDescription = r["Description"].ToString(),
  selectedSortOrder = r["SortOrder"].ToString()
  });
  listBoxCertificateSelected.DataContext = CertificateSelectedList;


... rest of code as attached.

Thanks in advance.

Answers (2)