Skip to main content

Data Validation In WPF Using IDataErrorInfo

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();  
     }  
   }  
 }  

Summary

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

Thanks
Kailash Chandra Behera

Comments

Popular posts from this blog

Generate QR Code in WPF

Introduction In my previous two blogs, we have discussed how to display generate and display various barcodes on the web page. In this blog, we are going to demonstrate how to Generate QR Code in the WPF application. Getting Started Here in the demonstration Generate QR Code in WPF , will generate QR code using third party library as there is not inbuilt library provided by Microsoft to generate QR code and will display in WPF image control, In the below, we will see the steps to display QR Code. As I mentioned in the above paragraph that there is no inbuild library provided by Microsoft to generate QR code, I have taken the help of the ZXing library which is a third party free library and available Nuget. This library provides various options to generate barcodes and QR Code from the user-friendly text. Generate QR Code in WPF Here are the steps to generate QR code and let's follow the steps to complete demonstrations. Demonstration:- Generate QR Code Open visual stud

Creating Application in Prism

Introduction This article explains an illustration of creating a windows application in Prism Library(WPF Prism). The solution includes recommended practices and techniques and is the basis for the procedures in Prism. This illustration created in the Visual Studio 2012, It can also developed in the visual studio 2008 and 2010, because wpf supports from .net framework 3.5 to latest version. Microsoft.Practices.Prism.dll. This assembly contains the implementation of the Prism Library core components such as modularity, logging services, communication services, and definitions for several core interfaces. It also contains the implementation of Prism Library components that target WPF applications, including commands, regions, and events. Microsoft.Practices.Prism.UnityExtensions.dll. This assembly contains base and utility classes you can reuse in applications built with the Prism Library that consume the Unity Application Block. For example, it contains a bootstrapper base class

WPF Binding

Introduction This blog describes WPF Binding and the measure elements exist with binding with XAML example in XAML and code-behind. Getting Started Binding helps in WPF to flow data from one object to another object, the object which fetches data is called source and the object which receives the data is called target. The Object a be a UI control or object of a class that means in binding you can bind a property of a class and property of another control to WPF UI controls as well. XAML Example <TextBox x:Name="sourceText" Grid.Row="0" /> <Button Grid.Row="1" Content="{Binding ElementName=sourceText, Path=Text}"/> Code Example Button btn=new Button(); Binding binding = new Binding("Text"); binding.Source = sourceText; btn.SetBinding(Button.ContentProperty, binding); In WPF binding has some measure properties or elements that we are using while developing application or projects, here we are going to d