Bind to IDataErrorInfo

image_pdfimage_print







//File:Window.xaml.cs
using System.Windows;
using System.ComponentModel;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DataContext = new Employee(){FirstName = “A”,Age = 26,};
}
}

public class Employee : INotifyPropertyChanged,IDataErrorInfo
{
private string firstName;
private int age;

public Employee()
{
FirstName = “A”;
}
public string FirstName
{
get
{
return firstName;
}
set
{
if(firstName != value)
{
firstName = value;
OnPropertyChanged(“FirstName”);
}
}
}

public int Age
{
get
{
return age;
}
set
{
if(this.age != value)
{
this.age = value;
OnPropertyChanged(“Age”);
}
}
}

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName){
if(this.PropertyChanged != null)
{
this.PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
}
}
public string Error
{
get
{
return string.Empty;
}
}

public string this[string propertyName]
{
get
{
string message = string.Empty;

switch(propertyName)
{
case “FirstName”:
if(string.IsNullOrEmpty(firstName))
message = “A person must have a first name.”;
break;

case “Age”:
if(age < 1) message = "A person must have an age."; break; default: break; } return message; } } } } [/csharp]