You can force validation on an object that uses data annotations. I have an 
extension method I use:

public static class ValidationExtensions
{
    public static bool TryValidate(this object subject, out ValidationResult 
result)
    {
        var context = new ValidationContext(subject, serviceProvider: null, 
items: null);
        var results = new List<ValidationResult>();

        if (Validator.TryValidateObject(subject, context, results, 
validateAllProperties: true))
        {
            result = null;
            return true;
        }

        result = results.First();
        return false;
    }
}

... which I call like this:

ValidationResult result;
if (!foo.TryValidate(out result)) return result;

You could conceivably turn that into a simple Boolean property on your object 
(“IsValid”) and bind your save button etc to that.

I’d probably wrap the whole thing in a ViewModel. Something like:

public class EditorViewModel<T>
{
    public T Subject { get; set; }
    public bool IsValid { get { ... } }
}

In fact, if you had a ViewModel you could have public properties that intercept 
the underlying subject’s properties and set an “IsDirty” property whenever they 
changed. That would address your second question.

Matt

From: Greg Keogh 
Sent: Wednesday, December 21, 2011 9:53 AM
To: 'ozWPF' 
Subject: Binding validation techniques

Folks, I am binding the properties of an EF4 created entity to a screen full of 
controls in the usual way. The default validation behaviour is acceptable for 
now, as exceptions from the setters or my validators put a red border around 
the guilty controls.

 

I have other controls like an error icon and the Save button which I’d like to 
bind to the validity and consistency of the *whole* entity. Is there some 
plumbing in place that can I use to bind controls to the overall state of the 
entity? For example, the Save button is disabled if there are 1 or more 
property errors.

 

Another thing I have to consider is giving an indication in the UI of any 
controls that have had their values changed. I’m wondering if there is a simple 
way of making controls automatically change colour when their value becomes 
changed/dirtied via binding. (Changing control colours is not normally a polite 
thing to do in the UI, but it would be okay for my demo).

 

Cheers,

Greg



--------------------------------------------------------------------------------
_______________________________________________
ozwpf mailing list
[email protected]
http://prdlxvm0001.codify.net/mailman/listinfo/ozwpf
_______________________________________________
ozwpf mailing list
[email protected]
http://prdlxvm0001.codify.net/mailman/listinfo/ozwpf

Reply via email to