Recently I came across an interface called IDataErrorInfo used for validation, and apparently it’s been around since the early days. I’ve never seen any use of it, or heard of it’s usage until now. It’s been used with WPF validation and integrates very seamlessly too.
- Step 1: Create data model with IDataErrorInfo
- Step 2: Databind the data to your input fields
- Step 3: Customize the Error Template to get different look and feel

As you can see from the screenshot, validation is triggered when the fields input fail the criteria. The “Add” button on the screen is also disabled/enabled in accordance to the validation via the use of WPF Command System.
Step 1: Creating data model with IDataErrorInfo
To get started with this, you first need a model that implements IDataErrorInfo, like so…
public class Customer : IDataErrorInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
#region IDataErrorInfo Members
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "FirstName")
{
if (string.IsNullOrEmpty(FirstName))
result = "Please enter a First Name";
}
if (columnName == "LastName")
{
if (string.IsNullOrEmpty(LastName))
result = "Please enter a Last Name";
}
if (columnName == "Age")
{
if (Age < = 0 || Age >= 99)
result = "Please enter a valid age";
}
return result;
}
}
#endregion
}
Looking at the interface implementation, we put in checks for the Property Names we are interested in validating, and return an error message for each one that failed the criteria. For example, we are validating that the first and last names are not empty fields.
Step 2: Databind the data to your input fields
So how does WPF know how to use this interface to validate the input fields? We make use of the coolness of data binding! Below is a snippet of a TextBox with data binding.
<textbox x:Name="tbFirstName" Grid.Row="0" Grid.Column="1" Validation.Error="Validation_Error"
Text="{Binding UpdateSourceTrigger=LostFocus, Path=FirstName,
ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
UpdateSourceTrigger specifies the condition for updating the source. I have set it to LostFocus instead of PropertyChanged, because PropertyChanged will degrade performance by triggering an update on every keystroke. There also another option called Explicit, meaning you have to trigger the update manually by calling the UpdateSource method.
ValidatesOnDataError is the super star behind all this. By flipping this flag on, the databinding will be able to communicate with any data types that implement IDataErrorInfo. (You might also want to read more about Validation.Error event and NotifyOnValidationError.)
Now that we understand how all these tie together, next question is how to display the error messages. By default, WPF notifies user of a error by highlighting the input field with a red border only. To display the error message or create a whole new look (like how I’ve done it), you need to do some work.
There’s a Validation static class in the WPF framework that’s designed for supporting data validation. You can attach it’s properties and event to any UIElement, such as the Validation.Errors property which holds a collection of error messages. We can now make use of this property to display our error message, for example in a ToolTip when user mouse overs the error icon.
Step 3: Customize the Error Template to get different look and feel
In WPF you can customize almost anything on the UI which is awesome. In order to customize our look and feel of the error, we change the ErrorTemplate of our textbox by defining a new style.
<style TargetType="{x:Type TextBox}">
<setter Property="VerticalAlignment" Value="Center" />
<setter Property="Margin" Value="0,2,40,2" />
<setter Property="Validation.ErrorTemplate">
</setter><setter .Value>
<controltemplate>
<dockpanel LastChildFill="true">
<border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="20" Height="20" CornerRadius="10"
ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
<textblock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white">
</textblock>
</border>
<adornedelementplaceholder Name="customAdorner" VerticalAlignment="Center" >
<border BorderBrush="red" BorderThickness="1" />
</adornedelementplaceholder>
</dockpanel>
</controltemplate>
</setter>
</style>
I’ve drawn the error icon very simply by wrapping a Border (with corner radius set properly) around a TextBlock. What’s of interest here is the AdornedElementPlaceholder, which like the name implies is a placeholder for an Adorner. So what is an Adorner? From my limited understanding, it’s basically a FrameworkElement that sits on top of your UI control on a different layer that is responsible for displaying visual cues. To me, it resembles a lot like the Decorator pattern, where you can enhance the look of your bound control without affecting it’s default state and behavior.
An example of customizing the Adorner is in the snippet above, where I put a red Border in it. When a validation error occurs, the Border appears around the control it is bound to, in this case the TextBox.
Lastly this line of Xaml code binds the ToolTip content to the first error message in the Validation.Errors collection.
ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
WPF has loads of features, and I’m enjoying the process of discovery. It’s been great fun playing with it, and there will be more to come. Happy Coding.
Updated Source
Download the sample code here.
| Share this post: |




May 12, 2009 at 6:16 am
[...] WPF: Validation made easy with IDataErrorInfo [...]
August 19, 2009 at 8:44 pm
Nice article!!
September 29, 2009 at 7:27 pm
Very nice article!
I have a couple of questions though
Why do your text boxes not show the error when the program is loaded?
I cannot seem to hide the error template after it has been shown, is it possible to hide the error template?
(setting visibility to “Hidden” on the dock panel, textbox, or placeholder does not seem to do it)
Thanks for helping me, I am new to WPF. Your validation example has saved me a ton of time.
September 29, 2009 at 10:57 pm
Hi Scott
thanks for the question. I’m also still learning WPF, there’s just too much!
I had a look at my code again, found a bug and fixed it too..lol. Anyways the reason why it’s not showing the error when program starts is due to the cause of binding the grid’s DataContext to a instance of a Customer as a resource key. I modified code to bind the grid to an initialized instance of a Customer in the code behind, and error triggered on startup. I’m not a 100% sure why that is, but that was my first suspicion.
for your 2nd question, because the error is triggered on and off via databinding and the IDataErrorInfo interface, to turn it off requires a valid value in the textbox. It’s triggered on LostFocus, so click somewhere else on the screen and validation will occur.
Hope that helps. You can download the updated sample code. I have modified it to trigger error on startup.
September 30, 2009 at 8:55 pm
Thank you for such a detailed answer and you are super fast too. I was thinking/hoping I would get the reply sometime next week as this post has been around awhile.
I am looking forward more to net 4.0 as there will be better support for validation. (well that and more)
You have helped me a ton. Thanks.
Have Fun,
-Scott