Set the Validationrules property of the binding to test the binding
<StackPanel>
<textbox x:name= "Txtage" fontsize= "foreground=" "Red" ></TextBox>
<textblock x:name= "errorsummary" fontsize= "foreground=" "Red" ></TextBlock>
</StackPanel>
Background code
Public partial class Mainwindow:window
{
Public MainWindow ()
{
InitializeComponent ();
Person p = new Person {age = $, Name = "Tom"};
Binding binding = new binding ("age") {Source = P};
Binding. NotifyOnValidationError = true;
Binding. UpdateSourceTrigger = updatesourcetrigger.propertychanged;
Rangevalidationrule RV = new Rangevalidationrule ();
Binding. Validationrules.add (RV);
This.txtAge.SetBinding (textbox.textproperty, binding);
This.txtAge.AddHandler (validation.errorevent, New Routedeventhandler (this. ValidationError));
}
void ValidationError (object sender, RoutedEventArgs e)
{
if (validation.geterrors (this.txtage). Count > 0)
{
This.txtAge.ToolTip = validation.geterrors (This.txtage) [0]. Errorcontent.tostring ();
This.errorSummary.Text = validation.geterrors (This.txtage) [0]. Errorcontent.tostring ();
//Can do everything here when validation error occurs
}
}
}
}
Again, we can set the validation in XAML.
<StackPanel>
<textbox x:name= "Txtage" fontsize= "+" foreground= "Red" validation.error= "Txtage_error" >
<binding notifyonvalidationerror= "True" path= "Age" updatesourcetrigger= "propertychanged" >
<Binding.ValidationRules>
<local:RangeValidationRule></local:RangeValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox>
<textblock x:name= "errorsummary" fontsize= "foreground=" "Red" ></TextBlock>
</StackPanel>
Background code:
public partial class Mainwindow:window
{
Public MainWindow ()
{
InitializeComponent ();
Person p = new Person {age = +, Name = "Tom"};
This. DataContext = p;
}
private void Txtage_error (object sender, Validationerroreventargs e)
{
if (Validation.geterrors (this.txtage). Count > 0)
{
This.txtAge.ToolTip = Validation.geterrors (This.txtage) [0]. Errorcontent.tostring ();
This.errorSummary.Text = Validation.geterrors (This.txtage) [0]. Errorcontent.tostring ();
You can do everything here when validation error occurs
}
}
}
Wpf-binding test of the data