views:

149

answers:

2

Hi,

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

A: 

Hi Mike,

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

Damian Schenkelman
Thanks for your comments Damian. I investigated INotifyDataErrorInfo a while back, but unfortunately it's unsupported in WPF. I am already using standard MVVM, the only sticking point is adding validation logic to my entity which I'm loathed to do. It does however appear to be the best compromise to get things working elegantly.
TheCodeKing
+1  A: 

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
{
    public string 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);
    }


}
TheCodeKing
Are you using poco classes for your entities?
dnndeveloper