4
votes

Im using DataAnnotation to validate input controls. But ValidatesOnExceptions only works when user type something in textbox and press Tab. (Basically on Lostfocus event).

but if user never enters anything in the textbox and click submit. It does not work. Like ASP.NET Page.IsValid property is there any property or method in Silverlight that i can use, that will validates all the controls on UI?

2

2 Answers

1
votes

Taking help from the URL provided by Terence, i have prepared the solution below for you. This you can use to make sure that all the properties are set before service call.

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
votes

I don't think, that there is a way to validate ALL UserControls which are visible on the page. But I would recommend you to have a look at the INotifyDataErrorInfo. This is, in my opinion, the best way to validate data in silverlight. With the INotifyDataErrorInfo approach you don't have to make changes in the view (like ValidatesOnException, ...) and you are able to validate against a WebService in an easy way (This is not possible with data annotations).

Have a look here: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/11/18/silverlight-4-rough-notes-binding-with-inotifydataerrorinfo.aspx

Hope this helps you.