Infragistics WPF controls

WPF Validation tutorial for the rest of us. Learn to use IDataErrorInfo to automatically validate your views.

WPF Succinctly Download

 

 

WPF Validation for mere mortals

I've recently jumped on the WPF bandwagon and I've fallen in love with this technology.  XAML is a fascinating animal indeed.  The declarative nature of the language leaves much to be explored.  There are many ways to solve the same problem.  On my quest for knowledge, I've been researching the intrinsic validation functionality of WPF.  Unfortunately, most every example I've ran across on blog posts and codeproject.com have been a bit too complex for my blood.  I find often that you need learn other subjects before you can begin to understand how the validation works.  Don't get me wrong, the examples are really nice.  However, when I'm learning something, I want a straight to the point example of the topic at hand.  It's with this idea in mind that I bring you a simple tutorial on WPF validation.

I will be illustrating this example using the MVVM (Model-View-ViewModel) Pattern.

 

Click here to download the entire source WPFMVVMValidation.zip (74.08 kb)

 Consider the following code 

The view MainWindow.xaml

<Window x:Class="ExceptionValidation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModel="clr-namespace:ExceptionValidation"
        Title="MainWindow" Height="350" Width="525" >
    <Window.Resources>
        <viewModel:MainWindowViewModel x:Key="mainViewModel"/>
    </Window.Resources>
    <StackPanel  DataContext="{Binding Source={StaticResource mainViewModel }}">
        <TextBlock>Enter total amount</TextBlock>
        <TextBox Width="200" Name="txtTotalAmount" >
            <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True">
                <Binding.ValidationRules>
                    <ExceptionValidationRule></ExceptionValidationRule>
                </Binding.ValidationRules>
            </Binding>
        </TextBox>
        <Button Content="Button" Height="28" Name="button1" Width="84" />
    </StackPanel>
</Window>
 

 

The viewmodel MainWindowViewModel.cs

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

namespace ExceptionValidation
{
    class MainWindowViewModel : ObservableCollection<Product>
    {
        public MainWindowViewModel()
        {
            Add(new Product { TotalAmount = 3 });
        }
    }
}
 

The model Product.cs

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

namespace ExceptionValidation
{
    public class Product : INotifyPropertyChanged , IDataErrorInfo
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private int _totalAmount = 5;

        public int TotalAmount
        {
            get { return _totalAmount; }
            set
            {
                _totalAmount = value;
                OnPropertyChanged("TotalAmount");
            }
        }

        public void OnPropertyChanged(string info)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (PropertyChanged != null)
            {
                handler(this, new PropertyChangedEventArgs(info));
            }
        }


        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get 
            {
                if (columnName == "TotalAmount")
                {
                    bool valid = true;
                    if (_totalAmount > 10)
                    {
                        valid = false;
                    }

                    if (!valid)
                    {
                        return "The total amount cannot exceed 10!";
                    }
                }

                return null;

            }
        }
    }
}

A brief introduction to MVVM 

As you can see, we have a XAML view, a viewmodel class, and a model.  The Model is a representation of an object's data.  In this instance, we are modeling a Product.  The viewmodel is an object that handles the change notification between properties in the model and elements on the view.  XAML properties, events, and bindings have the ability to tunnel (down the tree) as well as bubble (up the tree).  

Binding the ViewModel to the view.

In order to bind the ViewModel to the view, we must make it accessible to the view via XAML.  To accomplish this, we first have to import the namespace in which the viewmodel exists.  Examine the following code.

xmlns:viewModel="clr-namespace:ExceptionValidation"

Here is the equivalent in c#

using ExceptionValidation;

Once we've imported the namespace for use, we then need to define our MainWindowViewModel as a Resource of the current window.

<Window.Resources>
        <viewModel:MainWindowViewModel x:Key="mainViewModel"/>
</Window.Resources>

This allows us to declare an instance of the MainWindowViewModel class by using the associated Key "mainViewModel".

Binding the ViewModel

As stated before the ViewModel acts as a "go between" for the View and the Model.  In order for the view model to communicate with our XAML view, we will bind the ViewModel to the StackPanel's DataContext.

<StackPanel  DataContext="{Binding Source={StaticResource mainViewModel }}">

XAML's ability to tunnel properties down from parent to child will allow each element inside the stack panel to make use of the DataContext binding that we've just setup using the Window resource's key mainViewModel.

ObservableCollection<T>

The viewmodel inherits from ObservableCollection<Product>.  The ObservableCollection<T> generic class represents a collection that can be utilized by WPF databinding.  This is possible because the ObservableCollection<T> class raises an event when items are added and removed from the collection.

INotifyPropertyChanged

The model implements the INotifyPropertyChanged interface.  This interface provides an event in which to fire any time a model property is changed.  This event notifies the bound element in the view that the property has changed.

public event PropertyChangedEventHandler PropertyChanged;

 

public void OnPropertyChanged(string info)
{
    PropertyChangedEventHandler handler = PropertyChanged;

    if (PropertyChanged != null)
    {
        handler(this, new PropertyChangedEventArgs(info));
    }
}
 

IDataErrorInfo

The magic behind WPF validation comes from the implementation of the IDataErrrorInfo interface.  The interface implements the following members.  The this[columnName] indexer implements the logic of the validation rule.

//Not used by WPF
public string Error
{
    get { throw new NotImplementedException(); }
}

public string this[string columnName]
{
    get 
    {
        if (columnName == "TotalAmount")
        {
            bool valid = true;
            if (_totalAmount > 10)
            {
                valid = false;
            }

            if (!valid)
            {
                return "The total amount cannot exceed 10!";
            }
        }

        return null;

    }
}

The following XAML code binds the TotalAmount property of the first Product in the viewmodel's internal collection to the Text property of the TextBox element.  The ValidatesOnDataErrors attribute tells the textbox binding to raise an event when there is a valadation error.  When the event is raised, the bound element's template is changed to a new visual style that places a Red rectangle around the border of the TextBox.  When the error is corrected, the original template is restored. 

Binding.ValidatesOnDataErrors

<TextBox Width="200" Name="txtTotalAmount" >
    <Binding Path="[0].TotalAmount" ValidatesOnDataErrors="True">
    </Binding>
</TextBox>

In the provided example, if you enter a value greater than 10 into the text box and tab out of the textbox, you will see that an error is raised causing the red outline around the textbox.  If you correct the error by replacing the value with a number less than 10, the red outline will disappear.

This concludes my tutorial on WPF validation.  This is the very basic of validation methods.  There are many other advanced tutorials on the subject.  My next tutorial will involve utilizing custom validation attributes from the System.ComponentModel namespace to handle WPF view validation.

Thanks for reading!

~/Buddy James

kick it on DotNetKicks.com  



Comments (2) -

Lasoty
Lasoty
1/29/2013 3:24:11 AM #

HI, thanks for this exaple.
I've one question:
How set disable for IsEnabled button property when textbox has error?

Buddy James
Buddy James
1/29/2013 2:19:49 PM #

Thanks for reading!

You could simply create a property on the Product and or ViewModel and when the validation occurs, if the field is invalid, you can set the appropriate value on the ViewModel.  The ViewModel property should be a Boolean and you can bind it to the IsEnabled property on the Textbox.  So when the field is invalid, you mark a property as false on the ViewModel and the binding will then set the IsEnabled property.  Please let me know if you need a better explanation.  Thanks again for reading!

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About the author

My name is Buddy James.  I'm a Microsoft Certified Solutions Developer from the Nashville, TN area.  I'm a Software Engineer, an author, a blogger (http://www.refactorthis.net), a mentor, a thought leader, a technologist, a data scientist, and a husband.  I enjoy working with design patterns, data mining, c#, WPF, Silverlight, WinRT, XAML, ASP.NET, python, CouchDB, RavenDB, Hadoop, Android(MonoDroid), iOS (MonoTouch), and Machine Learning. I love technology and I love to develop software, collect data, analyze the data, and learn from the data.  When I'm not coding,  I'm determined to make a difference in the world by using data and machine learning techniques. (follow me at @budbjames).  

Related links

Month List