1

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.

Jordan
  • 9,642
  • 10
  • 71
  • 141

2 Answers2

2

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

Community
  • 1
  • 1
jpsstavares
  • 3,303
  • 5
  • 25
  • 32
0

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).

Andrei Pana
  • 4,484
  • 1
  • 26
  • 27
  • I'm creating AdjustWidthValidationRule inside XAML. As far as I know, you can only set dependency properties on dependency objects from within XAML. ValidationRule is not a dependency object. – Jordan Jan 31 '11 at 15:08
  • I think I understand what you say, but (sadly) the ValidationRule is not a DependencyObject, so you cannot bind, you can only give values. There is a trick though to overcome somehow this problem (look here: http://www.11011.net/wpf-binding-properties), but otherwise you'll have to stick to a more simple validation scheme. – Andrei Pana Jan 31 '11 at 15:19
  • Thanks, but I don't accept that. This method of WPF validation is unusable in the real world. All validation is based upon some sort of context, to offer no context at all for validation is just bad design. – Jordan Jan 31 '11 at 15:36