Tuesday, June 15, 2010

MvvmFoundation Extension – ValidationViewModelBase

Does some validation of the properties and has some structures to display the errors

MvvmFoundation @ codeplex

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace MvvmFoundation.Wpf
{
    /// <summary>
    /// ViewModelBase with Validation via IDataErrorInfo.
    /// </summary>
    public abstract class ValidationViewModelBase : ObservableObject, IDataErrorInfo
    {
        #region IDataErrorInfo Code
        /// <summary>
        /// Implement this in the Implementing Class. Throw an exception to allow validation to show on the UI.
        /// </summary>
        /// <param name="propertyName">The Property to Validate</param>
        public abstract string this[string propertyName] { get; }

        /// <summary>
        /// IDataErrorInfo.Error
        /// </summary>
        public string Error
        {
            get
            {
                if (HasValidationErrors)
                    return "Invalid";
                else
                    return "";
            }
        }

        /// <summary>
        /// Add an Error
        /// </summary>
        /// <param name="key">The key of the Error</param>
        /// <param name="value">The Value/Reason of the Error</param>
        public void AddError(string key, string value)
        {
            RemoveError(key);
            errorMessages.Add(key, value);
            RaisePropertyChanged("ValidationErrors");
            RaisePropertyChanged("HasValidationErrors");
        }

        /// <summary>
        /// Remove an Error by key
        /// </summary>
        /// <param name="key">the error key to remove</param>
        public void RemoveError(string key)
        {
            if (errorMessages.ContainsKey(key))
                errorMessages.Remove(key);
            RaisePropertyChanged("ValidationErrors");
            RaisePropertyChanged("HasValidationErrors");

        }

        /// <summary>
        /// String Representation of the Validation Errors
        /// </summary>
        public string ValidationErrors { get { return getErrorString(); } }

        /// <summary>
        /// Has Validation errors ?
        /// </summary>
        public bool HasValidationErrors { get { return errorMessages.Count > 0; } }

        #region Implementation Details

        private IDictionary<string, string> errorMessages = new Dictionary<string, string>();
        private string getErrorString()
        {
            StringBuilder value = new StringBuilder();
            foreach (KeyValuePair<string, string> item in errorMessages)
                value.AppendLine(string.Format("{0} - {1}", item.Key, item.Value));
            return value.ToString();
        }

        #endregion

        #endregion
    }
}

No comments:

Post a Comment