x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF" Height="136" Width="260">
x:Key="textBoxInErrorStyle"
TargetType="{x:Type TextBox}" >
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type Adorner}}}"/>
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}" />
Margin="4" Text="{Binding Path=Age, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"/>
//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;
}
}
}
}