Click here to Skip to main content
15,892,059 members
Articles / Desktop Programming / WPF

Attributes-based Validation in a WPF MVVM Application

Rate me:
Please Sign up or sign in to vote.
4.88/5 (30 votes)
28 Jul 2010CPOL6 min read 224.9K   7.2K   101  
Description of a method which uses attribute to perform user entry validation in a WPF MVVM application
using WpfFormsWithValidationDemo.Toolkit.ViewModel;

namespace WpfFormsWithValidationDemo.ViewModel
{
    public abstract class FormViewModelBase : ValidationViewModelBase
    {
        private bool isValid;

        private readonly string formName;

        /// <summary>
        /// Gets a value indicating whether the form is valid in its current state. If all properties
        /// wich validation are valid, this property returns true.
        /// </summary>
        public bool IsValid
        {
            get
            {
                return this.isValid;
            }
            protected set
            {
                this.isValid = value;
                this.OnPropertyChanged("IsValid");
            }
        }

        /// <summary>
        /// Gets the name of the form.
        /// </summary>
        public string FormName
        {
            get
            {
                return this.formName;
            }
        }

        protected FormViewModelBase(string formName)
        {
            this.formName = formName;
            this.PropertyChangedCompleted(string.Empty);
        }

        protected override void PropertyChangedCompleted(string propertyName)
        {
            // test prevent infinite loop while settings IsValid 
            // (which causes an PropertyChanged to be raised)
            if (propertyName != "IsValid")
            {
                // update the isValid status
                if (string.IsNullOrEmpty(this.Error) && this.ValidPropertiesCount == this.TotalPropertiesWithValidationCount)
                {
                    this.IsValid = true;
                }
                else
                {
                    this.IsValid = false;
                }
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior)
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions