Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF/XAML - Allowing ComboBox to have SelectedValue that isn't in ItemsSource

Tags:

combobox

wpf

xaml

So, I have a customer table, containing customer records, record, each of which has a customertype field. I also have a customertype table, containing the valid values for the customertype field.

And I need a WPF to do CRUD. (Create, Review, Update, Delete).

The obvious solution is to use a ComboBox, with its SelectedValue property bound to the customertype field, and its ItemsSource property bound to a list populated by a query of the customertype table.

Problem is, this doesn't work except in the sort of simple problem that you see in exercises.

The difficulty arises when you are viewing or editing a customer record that has a customertype value that isn't in the customertype table. This can happen by error, or it can happen because the customertype has been deprecated, and removed from the table.

What WPF does, in this circumstance, is to set the customertype field to null, because the SelectedValue isn't in the ItemsSource list. And that's a problem.

If you're only viewing, you should see the value that is in the table, regardless of whether it is in the list. If you're editing, you can make a reasonable argument that you should also show the value that is in the table, at least initially, though if you change the selection, you can't get what you started with.

So, any ideas? This is a problem that occurs on pretty much every edit/view form I have, so I'd prefer something that is reasonably clean at point of use. (That is, given the choice of complication in the XAML, everyplace I need to handle one of these fields, or complication in the code that backs the XAML I insert to handle one of these fields, I'd prefer the latter.)

like image 607
Jeff Dege Avatar asked Oct 22 '22 22:10

Jeff Dege


1 Answers

For this, I would suggest not binding your ItemsSource directly to the contents of the CustomerType table. Instead, merge an ItemsSource for Customer Type items in the Customer Type tables AND all the CustomerType values stored in Customer records which do not exist in the Customer Type table. Once the user goes from viewing into edit, update the collection to use only those items in the CustomerType table. When the user goes into view mode, switch back to the merged collection.

like image 63
Josh Avatar answered Jan 02 '23 20:01

Josh