2010-11-25 41 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 
     } 
    }  
} 
相关问题