Hi,
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 = "NameRequired")]
[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.