Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6755817
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T13:26:53+00:00 2026-05-26T13:26:53+00:00

I have built a base class for my view model(s). Here is some of

  • 0

I have built a base class for my view model(s). Here is some of the code:

public class BaseViewModel<TModel> : DependencyObject, INotifyPropertyChanged, IDisposable, IBaseViewModel<TModel>, IDataErrorInfo
{
        public TModel Model { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (this._disposed)
            {
                return;
            }

            if (disposing)
            {
                this.Model = default(TModel);
            }

            this._disposed = true;
        }
}

Okay, so I thought, let’s add some validation to the base class, which led me to the following article: Prism IDataErrorInfo validation with DataAnnotation on ViewModel Entities. So I added the following methods / properties (IDataErrorInfo) to my base class:

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 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 = System.Linq.Expressions.Expression.Parameter(typeof(object), "instance");

    var expression = System.Linq.Expressions.Expression.Lambda<Func<object, object>>(
        System.Linq.Expressions.Expression.ConvertChecked(
            System.Linq.Expressions.Expression.MakeMemberAccess(
                System.Linq.Expressions.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);
}

Okay, this brings me to the issue. The thing is the validation works perfectly, but lets say I have a property (within my view model called: Person) with a StringLength attribute. The StringLength attribute fires as soon as the application is opened. The user didn’t even have a chance to do anything. The validation fires as soon as the application is started.

public class PersonViewModel : BaseViewModel<BaseProxyWrapper<PosServiceClient>>
{
    private string _password = string.Empty;
    [StringLength(10, MinimumLength = 3, ErrorMessage = "Password must be between 3 and 10 characters long")]
    public string Password
    {
        get { return this._password; }
        set
        {
            if (this._password != value)
            {
                this._password = value;
                this.OnPropertyChanged("Password");
            }
        }
    }
}

I have noticed that this is caused by the IDataErrorInfo.this[string columnName] property, and in turn it calls the ValidateProperty method. But, I have no idea how to fix this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T13:26:53+00:00Added an answer on May 26, 2026 at 1:26 pm

    There could be two issues…

    Do you populate yopur Person instance by using the public properties?

    e.g.

      new Person { Password = null }
    

    This will fire the property changed notification for Password and will validate it.

    Some developers also set the properties in constructors…

    public class Person {
       public Person() {
          this.Password = null;
       }
    } 
    

    Recommended practise is to use private fields…

    public class Person {
       public Person() {
          _password = null;
       }
    
       public Person(string pwd) {
          _password = pwd;
       }
    } 
    

    OR

    You can create a flag in our view model base say IsLoaded. Make sure you set it to true only after your UI is loaded (probably in UI.Loaded event). In your IDataErrorInfo.this[string columnName] check if this property is true and only then validate the values. Otherwise return null.

    [EDIT]

    The following change did the job:

    public class PersonViewModel : BaseViewModel<BaseProxyWrapper<PosServiceClient>>
    {
        private string _password;
        [StringLength(10, MinimumLength = 3, ErrorMessage = "Password must be between 3 and 10 characters long")]
        public string Password
        {
            get { return this._password; }
            set
            {
                if (this._password != value)
                {
                    this._password = value;
                    this.OnPropertyChanged("Password");
                }
            }
        }
    
        public PersonViewModel(BaseProxyWrapper<PosServiceClient> model)
            : base(model)
        {
            this._username = null;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple model class Ad < ActiveRecord::Base has_many :ad_items end class AdItem
I have this Pin Model: class Pin < ActiveRecord::Base belongs_to :user belongs_to :image accepts_nested_attributes_for
I've built a simple Friend model, which allows Users to have multiple friends. Here's
I have to run a dozen of different build tests on a code base
I have built a number of asp.net servercontrols into a class library, & I
I am using a base Window class in a WPF project. In the code
I have a source base that, depending on defined flags at build time, creates
I have built an MSI that I would like to deploy, and update frequently.
I have built a simple C#.Net app on a M/C with only .Net FX
I have built a web page which contains a Crystal Report built using the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.