IntroductionWPF supports databinding but WPF did not have a valid customized validation of data. Later on with WPF 3.5, IDataErrorInfo interface provides the developer a way to show the customized error information. Steps to Implement the interface and provide the customize error message1. For databinding generally we have a real time object. Implement the IDataErrorInfo in the databinding class. public class Employee : IDataErrorInfo
{//include the required properties here}
2. For implementing the an interface all the interface, say IDataErrorInfo members are expected to be inherited IDataErrorInfo Members public string Error
{get { return null; }
}
//indexer property that checks the field name and //gives the validationpublic string this[string fieldName]
{get{string result = null;
//Required validation for each property//say If it is a name thenif (fieldName == "Name")
{if (this.Name == string.Empty) // Name is the property that exposes the field ‘Name’{
result = "Employee Name should not be blank";
}else{// check any other condition}
}return result; // result is the validation message}
}
3. To include this in XAML. a. Suppose we want to show the error message in tooltip the <Style x:Key="textBoxInError" 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}"/></Trigger></Style.Triggers></Style> b. Implementing the style for the text box <TextBoxx:Name="txtName" Style="{StaticResource textBoxInError}" ><BindingPath="Name"Mode="TwoWay" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged"NotifyOnSourceUpdated="True" NotifyOnTargetUpdated="True"><Binding.ValidationRules><ExceptionValidationRule/></Binding.ValidationRules></Binding></TextBox>c. Suppose If you want to show in a different textbox then <Border x:Name="bdrError" Margin="18,0,0,0" BorderBrush="Black" BorderThickness="2" CornerRadius="4" HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="Hidden"><Border.Background><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FFE80A17" Offset="0.536"/><GradientStop Color="#FF4B0C0C" Offset="1"/><GradientStop Color="#FF440808" Offset="0.005"/></LinearGradientBrush></Border.Background><TextBlock Text="{Binding ToolTip, ElementName=txtName, Mode=Default}" TextWrapping="Wrap" VerticalAlignment="Center" Margin="2" Foreground="#FFFAF2F2" FontSize="12"/></Border> Here the error information will be in a textbox u can animate it as required.
Expect this article will help the beginners.Happy Coding Sample Project SourceDownload source files -14 kb Download demo files -55 kb |