开发者

WPF: How to show error message in UI thrown from IValueConverter?

开发者 https://www.devze.com 2023-03-31 09:35 出处:网络
I implemented type CustomDoubleConverter which implements IValueConverter. I included it Converter={StaticResource customDoubleConverter} and corresponding resource in xaml-file.

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 con开发者_运维问答verting 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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号