我有一個表格:Silverlight的驗證與數據註釋不工作
<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>
和一個簡單的類此設置爲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);
}
}
我設置的數據上下文中有以下line in the code of the xaml:
DataContext = new Person {Name = "Joe User"};
我看到窗體上的數據,Name的標籤是粗體,表示需要編輯。但是,如果我清空該字段,或者將其設置爲無效長度的字符串,則不會在標籤本身或驗證摘要中進行驗證。我知道該文本框不會驗證,直到失去焦點,所以我點擊進入問候字段並輸入文本以確保我已經離開了其他文本控件。
我在這裏錯過了什麼?
答:
每@Alex Paven的回答,得到它與數據註釋工作,你可以使用:
[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"));
}
}
至於IDataErrorInfo的,我會考慮它。謝謝!
我同意。 IDataErrorInfo是一個更好的方法。在我目前的項目中,我有一個用於ViewModel的基類,它實現了IDataErrorInfo並調用使用FluentValidation庫的單獨驗證類。 – 2010-10-13 18:08:44