Is it appropriate to throw an exception from a CoerceValueCallback
if a given value is invalid or should only ValidateValueCallback
be used for DP-value-validation?
views:
41answers:
2first: It took me some thought to figure out that DP means Dependency Property.
second: As far as I understood, CoerceValueCallback is about fixing the value of the property to a given value, not about validating the value. Thus I'd opt for ValidateValueCallback for validation. Isn't that called anyways?
CoerceValue should indeed be used to fix a value (limit it between min and max for instance). I don't know whether throwing an exception will crash the application (you simply need to test it to find out) or will the framework handle it, but I wouldn't recommend it anyway because it would be against good coding practice.
Inorder to get extra info for ValidateValue you sometimes have to define some extra fields in your class. You can either bind those fields or set them before setting a value for your DP, then in your ValidateValue you can access those fields and get the extra info required. This extra field creating and passing info through intermediate "layers", seems to ok by Microsoft, because thats the way they have (short-sightedly) designed the framework.
I'll give you an example about the new WPF datagrid. If you go the standard route and define a RowValidationRule, you would expect to have access to the ItemsSource (your table) inorder to determine if a given value in your row already exists in the table. A very standard thing to do, but that information is not provided in the validation callback. So you have to create a field in your validation class to which you can bind the DataGrid's ItemsSource then you can access that field during validation...