Tutorial :WPF: Validating an object at submission



Question:

I am creating a WPF app using MVVM. The app manages tagged documents, called Notes, similar to blog posts. A Note has a Title, Text and a Tags collection. I want to validate a Note at the time it is submitted for two validation rules:

  • The Title can't be empty; and
  • The Note must have at least one Tag.

If validation fails, then the Note submission is canceled, the offending control in the UI should get the familair red outline, and a tool tip should explain the error. This all seems pretty straightforward if one wants to validate at the time a WPF control updates its binding source. Just create a custom ValidationRule and add it to the <Binding.ValidationRules> collection.

My problem is that I want to validate when the Note is submitted, not when controls update their binding sources. I know I can create a custom error message and display it in a MessageBox, but I would much rather use the red outline-tooltip approach--it's less intrusive. I figure there must be some simple way of doing this.

My question is pretty simple: What is the best way of performing on-submission validation in WPF/MVVM? How does my code instruct the UI to show the red error outline when validation fails? Thanks for your help.


Solution:1

One option is to use IDataErrorInfo in conjunction with WPF.

This would make it fairly easy to handle this scenario. You can just setup the IDataErrorInfo information at submission time, which would then cause the "red outline" (or other error theming) to appear.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »