deterministic and asynchronous field validation in WPF - wpf

In my MVVM based application I need to validate fields in a data entry from. If possible, I would like to use the standard WPF validation binding with ErrorTemplates.
However I would like the execution of the validation logic to be completely driven/triggered by the ViewModel (push to the View, not pull by the View) for the following reasons:
It must work asynchronously because validation logic might take a while to execute.
I need to be more deterministic and fine grained when validation logic is to be executed (e.g. only after the user clicks "Apply" or when the internal state changed in a way that entries suddenly become invalid)
I know Silverlight has INotifyDataErrorInfo which was introduced for exactly this purpose, but WPF doesn't. How can I still have my validation logic exectuted deterministically and asynchronously?

I posted an answer on your other question that apparently answered this one too.
Create a visualtree off of a control template in code

The built in validation for WPF and Silverlight is meant for quick client-side validation (such as Regex, parsing values, etc.).
If you need to go to a server to perform validation (or validation takes a long time), I would do that in a custom way. Such as when clicking a save button, etc.
So say you have a Save method in a ViewModel (you don't mention which MVVM framework you use):
public void Save()
{
//Do your validation, this might start a new thread (I use Async CTP myself)
//If validation is good, do your extra work, else display validation errors
}
I would just do all the work required for this within an action in your ViewModel

Related

A better way of managing a forms state?

I am new to Windows programming, as in my previous work I've mostly been involved with web technologies, and mostly in the backend. I have inherited a Winforms application, and one of my biggest nightmares is navigating through the endless states a form can be in.
To give you an example, a form has the state 'New' and 'Edit' depending on whether the user decided to Add or Edit a record. On this form, we have logic. If this texbox has a certain value, then these other textboxes are disabled, etc. This leads to endless chaining of these rules. So, a textbox's TextChanged event will influence another field. It in turn will fire X event that changes the state of other controls. It quickly devolves into a tangled mess that is impossible to maintain.
There has to be a better way... something simple and elegant that solves this problem. Any suggestions?
What I do is to have a single method called FormatControls(). In this method, I implement all the logic such as myTextbox.Enabled = mycheckBox.Checked and so on.
I call this method from my event handlers in the form, such as on checked changed, etc... I also call it when appropriate (ie, form newly loaded with no data, record loaded from database, etc). This has suited me well for many years now, it makes everything less complex.
You are correct, if you do not have a pattern in use it can turn into a too-complex thing.
You can try to use tha Application.Idle event to perform the enable disable logic and insulate this part from the business logic part.
Depending on what controls you have on your form, you might be able to do away with the separate textboxes and add/delete buttons and replace the whole works with a DataGrid.

Validation in WPF - Custom validation rule or IDataErrorInfo

As a new WPF programer I cant find the difference between two different way to validate user input:
What are the pros and cons of writing custom validation rule against implementing IDataErrorInfo, and vice versa? WhenShould I prefer one over the other?
Update:
Though I got my answer already, I found related article that may help others.
Basically, if you implement IDataErrorInfo, validation is implemented in the bound object, whereas if you implement validation rules, validation is implemented in objects attached to the binding.
Personally, if you're using MVVM, I think you'd have to be crazy to ever use anything except IDataErrorInfo. You want validation to live in the view model. If it's in your view model, it's centralized and it's testable. If it's in your view, then your validation logic can be wrong, or missing, and the only way to find it is by manually testing your view. That's a huge potential source of avoidable bugs.
There are places where it makes sense to use validation rules - if, for instance, you're building a UI around dumb objects (an XmlDataSource, for example). But for most production applications, I wouldn't go near it.
IDataErrorInfo
Validation logic keep in view model and easy to implement and maintain
Full control over all fields in the viewmodel
Validation Rule
Maintains the validation rule in separate class
Increase re-usability. For example you can implement required field
validations class reuse it throughout the application.
My opinion is, for common validation like required field validations, email address validattions you can use validation rule. If you need to do custom validations like range validations , or whatever custom validation use IDataerrorinfo.
You implement IDataErrorInfo to be able to use databinding with eas. You still build your custom validation rules.

WPF: Validating an object at submission

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.
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.

WPF: On-screen validation

What technique or library do you recommend for on-screen validation. That is, validation that is very visible to the user.
My requirements:
The validation must have a way to indicate to the user which fields have a problem.
The validation must have a way to indicate to the user how to fix the problem.
The validation must support comparatives like TextboxA > Textbox B.
The validation must support custom logic like "If CheckBoxC is checked, ListBoxD must be empty".
Sometimes, though not always, the user can save a record even though validation fails.
A combination of using IDataErrorInfo and ValidationRules should meet all of your criteria.
1 & 2 - can be handled easily using the standard WPF validation display techniques. For background info, I'd read Josh Smith's MSDN article, in particular, he shows a couple of ways to handle displaying validation information.
3 & 4 - can be handled easily via IDataErrorInfo. This interface lets you do any logic required in order to display validation, and can combine multiple properties in the validation rules.
5 - This is a matter of just tracking which rules prevent saving, and which do not. You'll need to handle this directly, but again, IDataErrorInfo can help here, since you can use a known set that allow saving, and have every other issue prevent it.
For simple cases, Validation Rules make life easy. They can be combined with IDataErrorInfo, however, for a nice mix of simple with extended logic for difficult cases.
You might find the BookLibrary and EmailClient sample applications of the WPF Application Framework (WAF) interesting. They use the IDataErrorInfo interface in combination with the .NET DataAnnotations attributes to define the validation rules.

Event on validation - WPF

I'm looking at developing a simple validation framework for WPF (the IDataErrorInfo method doesn't provide enough info for my needs), and am wondering if there is a way to be notified when a Property is going to validate? Please note that I need to know any time it is going to attempt validation rather than only when there is an error (so NotifyOnValidationError doesn't cut it)
Alternatively, my ultimate goal is simply to package more information than just an error string into my validations (How critical is the error, links for more info, etc.) while still allowing the validation to be driven by the data object (IDataErrorInfo style). If anyone can point me to a method for doing that then I'll be perfectly happy as well. :)
The problem you are going to run into is that WPF databinding and validation are tied to the IDataErrorInfo interface. The bindings check for validation based on the UpdateSourceTrigger property of the binding. So if your binding has "UpdateSourceTrigger=PropertyChanged" then everytime the property changes it calls the item["MyProperty"] which is where you would return information as to whether of not your property is valid. If it's set to "LostFocus" then it checks whenever the control loses focus. The binding also requires the "ValidatesOnDataErrors=True" in order for it to force validation on your bound entity.
I think your best bet would be to create a class that implements IDataErrorInfo and then supply more detailed information based on the severity of the error.
You need to look into inheriting from ValidationRule and then adding the new rule to all you binding objects.

Resources