I have a form:
<StackPanel x:Name="LayoutRoot">
<sdk:ValidationSummary />
<sdk:Label Target="{Binding ElementName=Greeting}" />
<TextBox x:Name="Greeting" Text="{Binding Greeting, Mode=TwoWay,
ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
<sdk:Label Target="{Binding ElementName=Name}" />
<TextBox x:Name="Name" Text="{Binding Name, Mode=TwoWay,
ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
</StackPanel>
And a simple class is defined as a DataContext ...
public class Person : INotifyPropertyChanged
{
private string _greeting;
private string _name;
public string Greeting
{
get { return _greeting; }
set
{
_greeting = value;
InvokePropertyChanged(new PropertyChangedEventArgs("Greeting"));
}
}
[Required(ErrorMessage = "Name must be provided")]
[StringLength(15, MinimumLength = 5,
ErrorMessage = "Name should be 5 to 15 characters")]
public string Name
{
get { return _name; }
set
{
_name = value;
InvokePropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
}
I set the data context with the following line in the code behind xaml:
DataContext = new Person {Name = "Joe User"};
I see the data in the form, and the label for Name is in bold, which indicates the need. However, if I empty the field or set it to a string of an invalid length, I do not get any validation on the label itself or on the validation summary. I understand that the text box is not checked until the focus is lost, so I click in the welcome box and enter the text to make sure that I left another text control.
What am I missing here?
Answer:
In response to @Alex Paven, answer so that it works with the annotations of the data you used:
[Required(ErrorMessage = "Name must be provided")]
[StringLength(15, MinimumLength = 5,
ErrorMessage = "Name should be 5 to 15 characters")]
public string Name
{
get { return _name; }
set
{
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name" });
_name = value;
InvokePropertyChanged(new PropertyChangedEventArgs("DisplayName"));
}
}
As for IDataErrorInfo, I will review it. Thank!