简体   繁体   中英

C#: wpf adding combobox item to multiple comboboxes

I'm trying to set multiple combo boxes to all having the same set of values to choose from (from the code side).

...
this.startTimeOptions = value;
this.cmbMonday.Items.Clear();
this.cmbTuesday.Items.Clear();

foreach (TimeObject time_option in this.TimeOptions) {
  ComboBoxItem new_item = new ComboBoxItem();
  this.cmbMonday.Items.Add(new_item);
  this.cmbTuesday.Items.Add(new_item);
} 
...

Currently when I try setting it I get this error:

"Element already has a logical parent. It must be detached from the old parent before it is attached to a new one."

So obviously they are complaining about not having a unique parent. But how do I get around this so that I have multiple comboboxes with the same list:

You need to create new ComboBoxItems for each ComboBox. Usually you would use one source collection and bind it to both ComboBoxes, they then will create the new items on their own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM