WPF ValidationRule: How do I know what I am validating?

391 views Asked by At

Ok, so I tried to create a ValidationRule to ensure that the set width of an item is within a given range for that item. Here is my attempt:

public class AdjustWidthValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        double dValue = (double)value;

        if (dValue < ??? || dValue > ???)
            return new ValidationResult(false, "Width is out of range!");

        return new ValidationResult(true, null);
    }
}

OK, now how am I supposed to know which element I'm supposed to be validating? This seems to only support hard-coded validation rules and doesn't seem to have any real world use; you need a context in which to validate. Am I not understanding something? Is this for person ages and field lengths alone? Am I supposed to provide a static state-machine? Is this the 1990's? I am very frustrated.

2

There are 2 answers

1
jpsstavares On BEST ANSWER

As an alternative you can use IDataErrorInfo on data validation. Here is a thread on that: Exception validating data with IDataErrorInfo with a MVVM implementation

3
Andrei Pana On

You validate the "value" object you get as an argument. You should know what kind of object is this. To make it more reusable and not to use hardcoded values, you can define properties in the AdjustWidthValidationRule class, something like:

public class AdjustWidthValidationRule : ValidationRule
{
    public double Max { get; set; }
    public double Min { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        double dValue = (double)value;

        if (dValue < Min || dValue > Max)
            return new ValidationResult(false, "Width is out of range!");

        return new ValidationResult(true, null);
    }
}

and you can give values to Max and Min in your xaml (or where you create the ValidationRule).