Question

I'm implementing data validation in WPF using the Prism MVVM framework. I'm using clean data Entities in the ViewModel which are being bound to the presentation layer.

 <TextBox Text="{Binding User.Email, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />

I've implemented a generic implementation of IDataErrorInfo in a base ViewModel class that runs validation against the DataAnnotation attributes on my Entity (in this case User).

The issue is that when binding to an Entity, the WPF framework looks for IDataErrorInfo on the Entity and not the ViewModel which is where I want this logic to exist. If I wrap my Entity with properties in my ViewModel then everything works, but I don't wish to compromise the use of Entities within the ViewModel.

Is there a way to tell WPF to look for the IDataErrorInfo in the ViewModel and not a child object that's being bound?

Thanks, Mike

Was it helpful?

Solution

The option I went with was to implement IDataErrorInfo explicitly in a base class which is extended by all ViewModels and Entities. This seems the best compromise to get things ticking over with WPF, and at least keeps the implementation of IDataErrorInfo hidden to callers so they at least appear clean. I expose a protected ValidateProperty which can be overridden if necessary in subclasses for any custom behaviour (such as for Password/PasswordConfirmation scenario).

public abstract class DataErrorInfo : IDataErrorInfo
{
    string IDataErrorInfo.Error
    {
        get { return null; }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get { return ValidateProperty(columnName); }
    }

    protected virtual string ValidateProperty(string columnName)
    {
         // get cached property accessors
            var propertyGetters = GetPropertyGetterLookups(GetType());

            if (propertyGetters.ContainsKey(columnName))
            {
                // read value of given property
                var value = propertyGetters[columnName](this);

                // run validation
                var results = new List<ValidationResult>();
                var vc = new ValidationContext(this, null, null) { MemberName = columnName };
                Validator.TryValidateProperty(value, vc, results);

                // transpose results
                var errors = Array.ConvertAll(results.ToArray(), o => o.ErrorMessage);
                return string.Join(Environment.NewLine, errors);
            }
            return string.Empty;
    }

    private static readonly Dictionary<string, object> PropertyLookupCache =
        new Dictionary<string, object>();

    private static Dictionary<string, Func<object, object>> GetPropertyGetterLookups(Type objType)
    {
        var key = objType.FullName ?? "";
        if (!PropertyLookupCache.ContainsKey(key))
        {
            var o = objType.GetProperties()
            .Where(p => GetValidations(p).Length != 0)
            .ToDictionary(p => p.Name, CreatePropertyGetter);

            PropertyLookupCache[key] = o;
            return o;
        }
        return (Dictionary<string, Func<object, object>>)PropertyLookupCache[key];
    }

    private static Func<object, object> CreatePropertyGetter(PropertyInfo propertyInfo)
    {
        var instanceParameter = Expression.Parameter(typeof(object), "instance");

        var expression = Expression.Lambda<Func<object, object>>(
            Expression.ConvertChecked(
                Expression.MakeMemberAccess(
                    Expression.ConvertChecked(instanceParameter, propertyInfo.DeclaringType),
                    propertyInfo),
                typeof(object)),
            instanceParameter);

        var compiledExpression = expression.Compile();

        return compiledExpression;
    }

    private static ValidationAttribute[] GetValidations(PropertyInfo property)
    {
        return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
    }


}

OTHER TIPS

Of course, I don't know your entire scenario, but I believe that wrapping your business entities (or model) using the ViewModel is a great part of the MVVM pattern, specially if you don't have a bindable model (a model to which you can bind directly). The wrapping can include error management information as in this scenario or other things such as customizing model display, etc.

That said, you can take a look at Prism's v4.0 MVVM RI, which uses the INotifyDataErrorInfo for validation, and should provide interesting insight on validation approaches.

I hope this helps.

Thanks, Damian

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top