ComboBox controls are great for selecting an item from a list of items; that’s literally what they’re there for. But what if you want to select an item, add it to somewhere, select another item, and add it again. There are few approaches you can take.
On SelectionChanged event handler, add to a list. Perhaps not the most user-friendly option.
Multi-select ComboBox, and each item has a CheckBox control to select/deselect. Okay, this is pretty neat.
But I want to take a different approach. I simply want to select an item old style, and then click a Button to add it to a list. This is actually pretty easy; on the Click event handler of the Button simply retrieve the SelectedItem of the ComboBox and add the value to a list. This is all good, but the problem is that the two controls stand alone. So I want to bundle them together and have a custom control, and we’ll use a UserControl for this purpose. I want it to look something like this:
So my UserControl would have two controls; a ComboBox and a Button. I want to be able to bind something from the ‘main’ (parent) to the UserControl. Then upon selecting something and clicking the Button, I want the UserControl to notify to the parent of the event occurrence, and also pass the selected value.
The UserControl’s XAML
The following binding will allow me to bind a list of data in the parent to the ComboBox in my UserControl.
And in the UserControls code behind:
Now in the MainWindow.xaml.cs:
Note that the above Names list is what’s bound to the UserControl from the main window XAML.