2010-11-25 40 views
4

使用DataAnnotation來驗證輸入控件。但ValidatesOnExceptions僅在用戶在文本框中輸入內容並按Tab鍵時才起作用。 (基本上是Lostfocus事件)。如何在silverlight中單擊按鈕時驗證輸入?

但如果用戶從不在文本框中輸入任何內容並點擊提交。這是行不通的。像ASP.NET Page.IsValid屬性是否有我可以使用的Silverlight中的任何屬性或方法,它將驗證UI上的所有控件?

回答

0

我不認爲,有一種方法來驗證頁面上可見的所有用戶控件。但我建議你看看INotifyDataErrorInfo。在我看來,這是驗證silverlight數據的最佳方式。使用INotifyDataErrorInfo方法,您不必在視圖中進行更改(如ValidatesOnException,...),並且您可以通過簡單的方式對WebService進行驗證(這對於數據註釋來說是不可能的)。

看一看這裏:http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/11/18/silverlight-4-rough-notes-binding-with-inotifydataerrorinfo.aspx

希望這有助於你。

+0

INotifyDataErrorInfo確實是Silverlight MVVM驗證的方法,但它仍不能解決Button單擊驗證控制問題 – 2011-02-01 13:41:44

1

從Terence提供的URL中獲得幫助,我爲您準備了以下解決方案。 這可以用來確保在維修呼叫之前設置所有屬性。

public class PersonViewModel : EntityBase 
{ 
    private readonly RelayCommand saveCommand; 

    public PersonViewModel(IServiceAgent serviceAgent) 
    { 
     saveCommand = new RelayCommand(Save) { IsEnabled = true }; 
    } 

    public RelayCommand SaveCommand // Binded with SaveButton 
    { 
     get { return saveCommand; } 
    } 

    public String Name // Binded with NameTextBox 
    { 
     get 
     { 
      return name; 
     } 
     set 
     { 
      name = value; 
      PropertyChangedHandler("Name");     
      ValidateName("Name", value); 
     } 
    } 

    public Int32 Age // Binded with AgeTextBox 
    { 
     get 
     { 
      return age; 
     } 
     set 
     { 
      age = value; 
      PropertyChangedHandler("Age"); 
      ValidateAge("Age", value); 
     } 
    } 

    private void ValidateName(string propertyName, String value) 
    { 
     ClearErrorFromProperty(propertyName); 
     if (/*SOME CONDITION*/)  
      AddErrorForProperty(propertyName, "/*NAME ERROR MESSAGE*/");   
    } 

    private void ValidateAge(string propertyName, Int32 value) 
    { 
     ClearErrorFromProperty(propertyName); 
     if (/*SOME CONDITION*/)  
      AddErrorForProperty(propertyName, "/*AGE ERROR MESSAGE*/");    
    } 

    public void Save() 
    { 
     ValidateName("Name", name); 
     ValidateAge("Age", age);   
     if (!HasErrors) 
     {     
      //SAVE CALL TO SERVICE 
     } 
    }  
} 
相關問題