Silverlight and DataAnnotations

When am I not using data controls like DataForm and DataGrid for any attributes like [Required], [StringLength] for my objects? Can they be used for validation outside of the above data controls?

If yes, could you please point me to some examples or documentation. I would like to prevent users from clicking OK if there are any validation errors and would like to avoid the exception metadata from the setters (maybe?).

+2


source to share


1 answer


Yes, they can be used for validation without using interface elements. Brad Abrams has a post about using these attributes for data forms, but it looks like you should be able to decouple some of the UI from its post from the core validation logic.

From the post, here is a sample property with validation logic added manually.



[DataMember()]
[Key()]
[ReadOnly(true)]
public int EmployeeID
{
    get
    {
        return this._employeeID;
    }
    set
    {
        if ((this._employeeID != value))
        {
            ValidationContext context = new ValidationContext(
                this, null, null);
            context.MemberName = "EmployeeID";
            Validator.ValidateProperty(value, context);
            this._employeeID = value;
            this.OnPropertyChanged("EmployeeID");
        }
    }
}       

      

+1


source







All Articles