2

I implemented type CustomDoubleConverter which implements IValueConverter. I included it Converter={StaticResource customDoubleConverter} and corresponding resource in xaml-file. It works fine.

The question is about error handling. I would like to check if UI string represents correct double. if no then show one of two messages on label depending on invalid input: empty string or other non-double string.

Which approach should be used to show custom error messages on UI form when error happens during type converting from string?

I tried to do via exceptions, but received unhandled exception. Tip: Do not throw an exception in a IValueConverter convinced me not to try exceptions any more.

I was able to check double after converting with correct handling of IDataErrorInfo interface in view model of MVVM. But it could be done after successful string to double conversion, which is not the case described above.

I have also ValidatesOnDataErrors="True" and ValidatesOnExceptions="True" for my text box.

I use MVVM approach for design if it is helpful (similar to the one described in WPF Apps With The Model-View-ViewModel Design Pattern).

In short:

I want to parse double from TextBox and show one of three error messages if any on UI label:

  • empty string (mentioned above),
  • invalid double string (mentioned above), and
  • negative number (does not mentioned above, but I handled it via IDataErrorInfo - it is not an issue).
sergtk
  • 10,714
  • 15
  • 75
  • 130

1 Answers1

2

It strictly depends on your UI design, or in other words, how you gonna notify about a problem to user. I would say use of Dependency Properties. For example.

Let's say user inserts a value in TextBox. The TextBox has a DataError dependency string property. Converter in case of fail, simply sets that property to appropriate user string (can be recovered form localized resource). One time property setuppped, TextBox becomes red, clears content and prints out the error text generated by converter.

I mean the idea is use Dependency Properties, how it will end up in final UI depends on your app design and your choices.

There is also another related SO link :

How to handle exception in Value converter so that custom error message can be displayed

Hope this helps.

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123
  • I will notify user via label on form, updated question. I use MVVM approach for design. – sergtk Aug 27 '11 at 22:07
  • 1
    ok, so you can set a dependency porperty on Label, and as Converter fails, it sets it. Label receives that signal becomes visible and shows the text passed from Converter. – Tigran Aug 27 '11 at 22:13
  • thanks, I will try, just have very small experience working with WPF. – sergtk Aug 27 '11 at 22:17
  • V! implemented via ValidationRule, found by last link in your answer. DependencyProperty seems more complex to use. Thanks! – sergtk Aug 27 '11 at 23:05