Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Validation vs. Converters

Tags:

c#

validation

wpf

With a converter, I can differentiate between at least 4 types of behavior regarding the update of the source value:

  • converting to a proper value (-> update source)
  • returning null (-> indicate error)
  • throwing an exception and activating the exception validation rule (-> indicate error)
  • returning Binding.DoNothing (-> don't update source, but don't indicate error eiter)

With a ValidationRule, I can only discriminate between success (-> update source) and failure (-> don't update source), but I cannot simulate the behavior that is associated with Binding.DoNothing

Is there a way to use ValidationRule in a way that is similar to the Binding.DoNothing behavior of converters?

like image 442
pmf Avatar asked Oct 15 '15 07:10

pmf


1 Answers

The intents of Converters and ValidationRules are pretty different. Converters take one value and make it into another. The 4 cases you mention are common enough for converting: do it; say it's null; blow up; ignore. However ValidationRules are yes/no things - they're valid or they're not. While it might make sense to have an "ignore" option, there isn't one.

The closest semantically would be to set IsValid = true in the constructor, but it's not precisely what you want.

public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
{
    try
    {
        // try normal setup/validation
    } 
    catch 
    {
        // handle exceptions, return false
    }
    // decide if you want to return false
    // return true (equivalent to nothing/ignore)
    return new ValidationResult(true, null);
}

Last thought I have is if you need special cases, and the try-catch or other logic will blow up. Only thing I can think of is a type check in the ValidationRule, which is pretty dubious since you're creating an undesirable dependency, but would bypass the problems. i.e.

if (value is SpecialType)
{
    return new ValidationResult(true, null);
}

HTH!

UPDATED

Or how about an IgnorableValidationRule?

public class IgnorableValidationRule : ValidationRule
{
    public bool Ignore { get; set; } = false;

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (Ignore) return new ValidationResult(true, null);

        return new ValidationResult(false, "Why does everyone ignore me?");
    }
}

<TextBox.Text>
    <Binding Path="Data">
        <Binding.ValidationRules>
            <local:IgnorableValidationRule Ignore="True"/> <!-- na na -->
        </Binding.ValidationRules>
    </Binding>
</TextBox.Text>
like image 121
Todd Sprang Avatar answered Nov 11 '22 14:11

Todd Sprang