Using DataAnnotations for validation in MVVM
I've discovered the new data annotation features of SL3 and I'm using them for user input validation.
I've got inputs like these:
<dataInput:Label Target="{Binding ElementName=inputName}"/>
<TextBox
x:Name="inputName"
Text="{Binding RequestDemoData.Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}"/>
<dataInput:DescriptionViewer {Binding ElementName=inputName}"/>
and my model looks like that:
[Display(ResourceType = typeof(Resources.Resources), Name = "Name", Description = "NameDescription")]
[Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "NameReq开发者_JAVA百科uired")]
[RegularExpression(@"^[^0-9]*[a-zA-Z]+[^0-9]*$", ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "NameError")]
public string Name
{
get
{
ValidateProperty("Name", _name);
return _name;
}
set
{
if (_name != value)
{
ValidateProperty("Name", value);
_name = value;
OnPropertyChanged("Name");
}
}
}
So far, so good. If the user inputs some wrong data, I get an error message when he/she focuses out. The issue is that I've got a submit button bound to an ICommand
and I can't work out how to make the error message appear when the user clicks it.
The bad way is to add some code-behind and do GetBindingExpression(foo).UpdateSource()
and that would sort it out. The downside is that it's completely unmanageable and I hate to habe code-behind on my viewa.
http://www.thejoyofcode.com/Silverlight_Validation_and_MVVM_Part_II.aspx proposed a solution and I'm going to follow it but I'd like to know if there isn't an easier way.
Cheers.
Unfortunately, there is not much of a better way to do this. The only way to have the UI update itself based on validators is in the setter of the binding.
This, I believe, is a huge limitation of the validation system in Silverlight. That JoyOfCode article is really the best way to go about it.
I would also recommend the article by the same publisher where you can bind errors to your viewmodel, but it doesn't work the other way around.
I have also used Josh's approach on a very large scale LOB application and whilst it is messy it does work. The Validation Context in particular is likely to get you out of a few scraps with more complex logic.
精彩评论