WPF validation rule - .net 4.0

Fuma

Executive Member
Joined
Jul 9, 2007
Messages
5,377
Reaction score
360
Location
Pretoria
So I started with WPF and it been a painful experience, coming from WinForms.

I have text boxes that I'm binding to my object's properties. I'm trying to use data annotations to validate required fields and and:
public class Person
{

[Required(ErrorMessage = "Enter name!!!.")]
public string Name{ get; set; }

}
my xaml looks something like:
.
.
.
<TextBox x:Name="txtName" Text="{Binding Path=Name}" />
<Button Content="Submit" x:Name="btnSubmit" />

When I click on the button, I want that ErrorMessage "Enter name!!!." to display, and obviously return false.
Can someone tell me how to connect the pieces.
Will the message come as a popup (MessageBox.Show) or will I need to create labels next to each required textbox.
In asp.net webforms you can use requiredfieldvalidator for this.
 
This is easy. You basically need to impliment the IDataErrorInfo interface. Doing a quick search will return a few samples on this:

http://www.bing.com/search?q=wpf+IDataErrorinfo+dataanotations&qs=n&sk=&form=QBRE

The following blog gives a very basic sample on how to use it:
http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/

The best implimentation I have found and which works incredibly well is this one:
http://weblogs.asp.net/marianor/arc...tes-and-idataerrorinfo-interface-in-mvvm.aspx

Edit: Just remember to always have a message in the ErrorMessage field, otherwise WPF might act a bit weird.
 
Last edited:
This is easy. You basically need to impliment the IDataErrorInfo interface. Doing a quick search will return a few samples on this:

http://www.bing.com/search?q=wpf+IDataErrorinfo+dataanotations&qs=n&sk=&form=QBRE

The following blog gives a very basic sample on how to use it:
http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/

The best implimentation I have found and which works incredibly well is this one:
http://weblogs.asp.net/marianor/arc...tes-and-idataerrorinfo-interface-in-mvvm.aspx

^^This. I implement the IDataErrorInfo.
 
So I started with WPF and it been a painful experience, coming from WinForms.

Welcome to WPF by the way. You may as well leave all your winforms experience at the door, it's no longer needed unfortunately. The move to WPF is painful, but totally worth it if you put in the hard yards. I've been using WPF for 3 years now, and can't go back to winforms.

Two guys you want to follow, and read through all their old posts and articles to play catch up:

Josh Smith (this guy has a wealth of info on WPF in codeproject). I think he used to work for MS on WPF a long time ago. He knows everything there is to know about MVVN with WPF:

His Blog: http://joshsmithonwpf.wordpress.com/

Dr. WPF
http://drwpf.com/blog/

nJoy
 
Top
Sign up to the MyBroadband newsletter
X