我發現了SL3的新數據註釋功能,並將其用於用戶輸入驗證。在MVVM中使用DataAnnotations進行驗證
我有輸入這樣的:
<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}"/>
和我的模型看起來像這樣:
[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");
}
}
}
到目前爲止,一切都很好。如果用戶輸入了一些錯誤的數據,當他/她關注時我會收到一條錯誤消息。問題是我有一個綁定到ICommand
的提交按鈕,我無法確定如何在用戶單擊它時顯示錯誤消息。
不好的方法是添加一些代碼隱藏,並做GetBindingExpression(foo).UpdateSource()
,這將整理出來。缺點是它完全無法管理,我討厭在我的視圖中隱藏代碼隱藏。
http://www.thejoyofcode.com/Silverlight_Validation_and_MVVM_Part_II.aspx提出了一個解決方案,我將遵循它,但我想知道是否沒有更簡單的方法。
乾杯。