views:

70

answers:

0

This problem has several ways of being solved and that explains the complex title.

I have a object that can be changed in a form in my WPF app. I wan't the save button to be Unenabled when there are validation errors in the form.

I'm using IDataErrorInfo to notify to UI when there are errors and then I wan't a trigger on DataTemplate to check for any of the errors. Problem here is the trigger won't find any errors, likely because they are tied to each individual property and not the whole object.

I also have a IsValid property but can't use that as a property for a trigger because it's not a dependencyProperty. It looks like this:

public bool IsValid
    {
        get
        {
            return (GetRuleViolations().Count() == 0);
        }
    }

And the IDataErrorInfo part is like this:

public string Error
    {
        get { return null; }
    }

    public string this[string name]
    {
        get
        {
            string result = null;

            if (this.GetRuleViolations().Where(v => v.PropertyName == name).Count() > 0)
            {
                result = this.GetRuleViolations().Where(v => v.PropertyName == name).First().ErrorMessage;
            }

            return result;
        }
    }

and then there is the GetRuleViolation method where the real validation is done.

public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (string.IsNullOrEmpty(Name))
            yield return new RuleViolation("Plant must have a name", "Name");

        if (string.IsNullOrEmpty(PostCode))
            yield return new RuleViolation("PostCode can't be empty", "PostCode");

        if ( PostCode.Length != 3 )
            yield return new RuleViolation("PostCode must have 3 letters", "PostCode");

        yield break;
    }

Now if I could turn the IsValid property into a DependencyProperty this could really work out well. However I don't understand them well and in the examples I've seen they are all dependent on some hidden field so I can't see a way to tie it to a method count.

Other way is if I could check if the whole object has some item that has a DataError but I don't know how.