WPF Strongly Typed ComboBox

This is a hack more than an elegant solution but given the WPF architecture it has been the only way I've found to
make a ComboBox strongly typed. The problem I had is that I use to access the SelectedItem ComboBox's
property casting the object or using the as operator expecting a certain type of object and it could
be ambiguous. At least it is tired to find out whether there is no SelectedItem or you are casting to the wrong type.
I mean, if you populate the combobox with an object of type A and access the SelectedItem expecting type A,
then a change in the combobox items type will break the application during runtime. It could be difficult to detect.
By using the Boxerp.Controls.GenericComboBox template you get a strongly type combo to avoid that situation.

The idea is to wrap the ComboBox within the GenericComboBox keeping track of the items inserted in the combo
and casting the SelectedItem property. The problem is that XAML doesn't allow for generics so you cannot put the
GenericComboBox in the XAML but you can put a Grid or a Panel as a placeholder for the combobox.
You must place the combo insde the grid programmatically:

  • GenericComboBox<int> _myCombo = new GenericComboBox<int>();
  • _myComboGrid.Children.Add(_myCombo);
  • _myCombo.AdjustDimensions();


The classes are available to download in the Boxerp svn:
InterceptedList.cs

GenericComboBox.xaml

GenericComboBox.xaml.cs

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.