views:

41

answers:

2

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?

A: 

first: 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?

Ruedi Steinmann
CoerceValueCallback gets information about the DP and the instance the DP is set for. This can be usefull in some cases. ValidateValueCallback however gets only the value that should be validated. In "normal" situations it is clear that I use ValidateValueCallback, but if the extra information is handy/desired, is it legal to use the CoerceValueCallback to validate?
HCL
+1  A: 

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...

Marko
+1 Thanks for your answer. As far as I remember, I have tested the behaviour that is shown if an exception is thrown in CoerceValueCallback. It did what I have desired, but I haven't used it in productive code because it looked to me unclean. However the solution with setting additional fields before the validation seems to me also not very convenient and is in some situations also impossible. But I think it is like your wrote, using CoerceValueCallback is not to be used because it is not intended to do this (based on the name of the callback and without having more information to this (msdn))
HCL