13/08/13

Validation In MVVM

First Create Model Inside ValidationMVVM Project
namespace Models
{
    using System;
    using System.ComponentModel;
   
    class Model : IDataErrorInfo, INotifyPropertyChanged
    {

        private string customerName;

        public string CustomerName
        {
            get
            {
                return customerName;
            }
            set
            {
                customerName = value;
                NotifyPropertyChanged("CustomerName");
            }
        }


        private int customerAge;
        public int CustomerAge
        {
            get
            {
                return customerAge;
            }
            set
            {

                customerAge = value;
                NotifyPropertyChanged("CustomerAge");
            }
        }


        #region INotifyPropertyChanged Members

   
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises the PropertyChanged event for a property.
        /// </summary>
        /// <param name="propertyName">The name of the property that has changed.</param>
        protected void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        #region IDataErrorInfo Members

        string IDataErrorInfo.Error
        {
            get
            {
                return null;
            }
        }

        string IDataErrorInfo.this[string propertyName]
        {
            get
            {
                return GetValidationError(propertyName);
            }
        }

        #endregion

        #region Validation

        static readonly string[] ValidatedProperties =
        {
            "CustomerName",
            "CustomerAge"
        };

        public bool IsValid
        {
            get
            {
                foreach (string property in ValidatedProperties)
                    if (GetValidationError(property) != null)
                        return false;

                return true;
            }
        }

        string GetValidationError(String propertyName)
        {
            string error = null;

            switch (propertyName)
            {
                case "CustomerName":
                    error = ValidateCustomerName();
                    break;
                case "CustomerAge":
                    error = ValidateCustomerAge();
                    break;
                default :
                   error = null;
                    break;
            }

            return error;
        }

        private string ValidateCustomerName()
        {
            if (String.IsNullOrWhiteSpace(CustomerName))
            {
                return "Customer name cannot be empty.";
            }

            return null;
        }
        private string ValidateCustomerAge()
        {
            if (CustomerAge < 18)
            {
                return "Customer Age above 18.";
            }
            return null;
        }
        #endregion

    }
}

Now time to create View
<Window x:Class="Mvvm.Session03.IDataErrorInfo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Mvvm.Session03.IDataErrorInfo.ViewModels"
        Title="MainWindow" Height="350" Width="525">
   
    <Window.Resources>
        <local:ViewModel x:Key="mainviewModel"/>
    </Window.Resources>
   
    <StackPanel DataContext="{StaticResource mainviewModel}" Margin="10">
        <TextBox Name="CustomerName"
                 Text="{Binding Model.CustomerName, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"
                 Validation.ValidationAdornerSite="{Binding ElementName=AdornerSite}"/>
       
        <Label Name="AdornerSite"
               FontWeight="Bold"
               Foreground="Red"
               Content="{Binding ElementName=CustomerName, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>

        <TextBox Name="CustomerAge"
                Text="{Binding Model.CustomerAge,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}"
                 Validation.ValidationAdornerSite="{Binding ElementName=AdornerSiteAge}"/>

        <Label Name="AdornerSiteAge"
               FontWeight="Bold"
               Foreground="Red"
               Content="{Binding ElementName=CustomerAge, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
    </StackPanel>
</Window>

check for glue between model and view
that is viewmodel

namespace ViewModels
{
    using System;
    using System.ComponentModel;
    using Models;

    class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            Model = new Model()
            {
                CustomerName = "Raju",
                CustomerAge = 20
            };
        }

        public Model Model
        {
            get;
            set;
        }

        #region INotifyPropertyChanged Members

        /// <summary>
        /// Occurs when a property that supports change notification has changed.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises the PropertyChanged event for a property.
        /// </summary>
        /// <param name="propertyName">The name of the property that has changed.</param>
        protected void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
}.

No comments:

Post a Comment