Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IValueConverter and validation on exception

Tags:

c#

silverlight

I'm using custom DateTimeToString : IValueConverter

In my ConvertBack method I'm throwing Exception when conversion fails, however it is not displayed as validation failure (it is an unhandled application exception), and I want to show it as validation problem (red border).

In short I want it to work like DateTime+Texbox when it shows validation message ("input string was in incorrect format") but with my custom IValueConverter.

like image 614
Alex Burtsev Avatar asked Jun 22 '11 12:06

Alex Burtsev


2 Answers

Although I agree with winSharp93's answer https://stackoverflow.com/a/6439620/29491 in principle, I've found that if you return a ValidationResult from the ConvertBack method, you will get the expected Validation behaviour.

You will need to use the TryParse or TryParseExact methods as indicated below or catch the FormatException if you are using the Parse methods.

DateTime result;
if (DateTime.TryParseExact(dateString, dateFormat, culture, DateTimeStyles.None, out result))
{
    return result;
}
else 
{
    return new ValidationResult("Date string format error");
}
like image 179
Martin Hollingsworth Avatar answered Sep 20 '22 01:09

Martin Hollingsworth


Just found out this is a known behavior of ivalueconverter. It is because ivalueConverter isn't part of the 'Validation pipeline' in Silverlight. Because the ivalueConverter throws exceptions before it gets to the Validation logic, it isn't treated as a Validation error. There is a post in Silverlight forum for the same problem. Some one has started a request at dotnet.uservoice. Personally I think this should be fixed/improved because converter is a logical place for validation error. After all, how often we get a conversion error? A lot!

like image 27
Liang Avatar answered Sep 18 '22 01:09

Liang