在Silverlight中,如何在单击按钮时验证输入?

4

我正在使用DataAnnotation来验证输入控件。但是当用户在文本框中键入内容并按Tab键时,ValidatesOnExceptions只有在失去焦点事件上起作用。

但是如果用户从未在文本框中输入任何内容并单击提交,则不起作用。就像ASP.NET Page.IsValid属性一样,在Silverlight中是否有任何属性或方法可以使用,以验证UI上的所有控件?

2个回答

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
        }
    }       
}

0

我认为,没有办法验证页面上所有可见的UserControl。但是我建议您查看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

希望这能帮到您。


INotifyDataErrorInfo确实是Silverlight MVVM验证的方法,但它仍然无法解决在按钮点击时进行验证控件的问题。 - Sharjeel Ahmed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接