WPF Data Validation using IDataErrorInfo

Kailash Chandra Behera | Thursday, January 26, 2017

Introduction

In my previous article we had discussed, how data validation is handled in WPF. Now This article defines in detail about and demonstrates how to use IDataErrorInfo interface.

Getting Started

IDataErrorInfo interface comes under System.ComponentModel namespace and it enables to provide basic custome data validation in client side.It defines two read-only properties: an indexer property, with the property name as the indexer argument, and an Error property. Both properties return a string value.

  1. Indexer Property:-It allows the view model or model class to provide an error message specific to the named property. An empty string or null return value indicates to the view that the changed property value is valid.
  2. Error Property:-The Error property allows the view model or model class to provide an error message for the entire object.
In View to implement validation through IDataErrorInfo interface, need to set the ValidatesOnDataErrors property on the data binding to true, because it ensures that the data binding engine will request error information for the data-bound property.

For Example:-

 <Window x:Class="IDataErrorInfoExample.MainWindow"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
     Title="MainWindow" Height="350" Width="525">  
   <Grid>  
     <TextBox Width="200" Height="25" Text="{Binding Path=Student.Name, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True }">  
     </TextBox>  
   </Grid>  
 </Window>  
For error reporting WPF uses Validation.Errors collection. It provides a binding source for error reporting in the user interface. Several controls bind to this collection from their default control templates. Error reporting can be customized using Binding.NotifyOnValidationError property. The value of this property need to set to trueand handle the FrameworkElement.BindingValidationError event. Even by replacing the default templates with customized versions, error reporting can be customized.

Examples:-

The following example code demonstrates how to implement IDataErrorInfo. This example validates each property bound with UI controls, displays red background and tooltip text if validation fails
Examples:-Entity Class
 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 namespace IDataErrorInfoExample  
 {  
   public class Student : IDataErrorInfo  
   {  
     private int _rollno;  
     public int RollNo  
     {  
       get { return _rollno; }  
       set { _rollno = value; }  
     }  
     private string _name;  
     public string Name  
     {  
       get { return _name; }  
       set { _name = value; }  
     }  
     public string Error  
     {  
       get { throw new NotImplementedException(); }  
     }  
     public string this[string columnName]  
     {  
       get  
       {  
         if (columnName == "RollNo")  
         {  
           if (this.RollNo <= 0)  
             return "Invalid student roll no.";  
         }  
         if (columnName == "Name")  
         {  
           if (string.IsNullOrEmpty(this.Name))  
             return "Enter name of student";  
         }  
         return "";  
       }  
     }  
   }  
 }  
Examples:-XAML Code
 <Window x:Class="IDataErrorInfoExample.MainWindow"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
      xmlns:sdk="http://schemas.microsoft.com/netfx/2009/xaml/presentation"  
     Title="WPF Data Validation: IDataErrorInfo" Height="350" Width="525">  
   <Window.Resources>  
     <Style x:Key="txtstyle" TargetType="TextBox">  
       <Style.Triggers>  
         <Trigger Property="Validation.HasError" Value="true">  
           <Setter Property="ToolTip"  
      Value="{Binding RelativeSource={x:Static RelativeSource.Self},  
 Path=(Validation.Errors)[0].ErrorContent}"/>  
           <Setter Property="BorderBrush" Value="Red"></Setter>  
           <Setter Property="BorderThickness" Value="1"></Setter>  
         </Trigger>  
       </Style.Triggers>  
     </Style>  
   </Window.Resources>  
   <Grid>  
     <Grid.RowDefinitions>  
       <RowDefinition Height="80"/>  
       <RowDefinition Height="50"/>  
       <RowDefinition Height="50"/>  
       <RowDefinition Height="50"/>  
       <RowDefinition Height="*"/>  
     </Grid.RowDefinitions>  
     <Grid.ColumnDefinitions>  
       <ColumnDefinition Width="50"/>  
       <ColumnDefinition Width="*"/>  
     </Grid.ColumnDefinitions>  
     <TextBlock Text="Student Form" TextAlignment="Center" Margin="0,20" FontSize="20" FontWeight="ExtraBold" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></TextBlock>  
     <TextBlock Text="Roll No." Grid.Row="1" HorizontalAlignment="Right" VerticalAlignment="Center"></TextBlock>  
     <TextBlock Text="Name." Grid.Row="2" HorizontalAlignment="Right" VerticalAlignment="Center"></TextBlock>  
     <TextBox Style="{StaticResource txtstyle}" Text="{Binding Path=RollNo, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Grid.Row="1" Grid.Column="1" Margin="5"></TextBox>  
     <TextBox Style="{StaticResource txtstyle}" Text="{Binding Path=Name, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" Grid.Row="2" Grid.Column="1" Margin="5"></TextBox>  
   </Grid>  
 </Window>  
Examples:-MainWindow C#
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.Windows;  
 using System.Windows.Controls;  
 using System.Windows.Data;  
 using System.Windows.Documents;  
 using System.Windows.Input;  
 using System.Windows.Media;  
 using System.Windows.Media.Imaging;  
 using System.Windows.Navigation;  
 using System.Windows.Shapes;  
 namespace IDataErrorInfoExample  
 {  
   /// <summary>  
   /// Interaction logic for MainWindow.xaml  
   /// </summary>  
   public partial class MainWindow : Window  
   {  
     public MainWindow()  
     {  
       InitializeComponent();  
       this.DataContext = new Student();  
     }  
   }  
 }  

Related Articles

  1. Data Validation in WPF
  2. WPF Round Corner Button with click effects
  3. Round Corner PasswordBox in WPF
  4. Round Corner TextBox in WPF
  5. WPF Custom Datagrid Control(Filterable)
  6. WPF Round Corner ListBox
  7. Custom RadioButtonListBox With Image
  8. RadiobuttonList in WPF
  9. Custom CheckedListBox in WPF

Summary

This article discussed and demonstrated about IDataErrorInfo interface and how to use it, hope this article may helpful to you

Thanks