Friday, August 27, 2010

Converters does not live well with Data Validation

If you throw an exception in a IValueConverter, then it will be propagated to UI, instead of caught by Data Validation code (Set ValidateOnException=True). Basically you have no way around this. So the only other choice is to add data annotations and do the validation there as suggested in this discussion.
// Confine value between 0 and 1

// type conversion error will be thrown as well

[Range(0,1)]
public int IntValue
{
get { return _intvalue; }
set
{
Validator.ValidateProperty(value,
new ValidationContext(this, null, null) { MemberName = "IntValue" });
_intvalue = value;
}
}


There is another article that describes it better, even though the title says "Silverlight 4 vs Flex 4: Data Validation". (I actually clicked this link while researching this problem, but did not read it until I figured out the problem, and that's after a long time. :()

No comments: