I have a form, backed by a ViewModel that’s wrapping an ORM object that is mapping a database record that contains a “territory” field.
The business logic for this field is toggled by a “ValidateTerritory” configuration flag. If the flag is turned on, then the field has to contain one of the values in the Territories table. In this case, my view should contain a ComboBox that is populated with these territories. This I could handle, simply enough: include a ValidTerritories property on the ViewModel that is populated from the database, and bind the ComboBox’s ItemsSource to that property. And, of course, bind the ComboBox’s SelectedValue to the territory field in the ORM.
The problem is that if the “ValidateTerritory” flag is turned off, there are no validation rules on this field. It’s a plain text field containing any unconstrained value. In which case my view should contain a TextBox, with it’s Text property bound to the field in the ORM.
The question is: what is the cleanest way of handling this – toggling the control on the form from one type to another, based on the value of that configuration object?
I’d consider using a
ContentControlthat binds to the ‘full’ data (i.e.Content="{Binding }") and has aDataTemplateSelectorthat returns a data template containing aComboBox(with the right bindings) or a data template containing aTextBox(again, the bindings are in theDataTemplate).This way you don’t have validation issues, no performance cost of loading a control that is collapsed and more flexibility in the future to have other controls in that role (maybe, an
AutoComplete).