Tuesday, January 27, 2009

How to add a binding to a property on a ValidationRule

You can't add bindings to properties on classes that derive from ValidationRule in the normal way. This is because validation rules don't sit in an inheritance context and don't derive from DependencyObject.

Fortunately, this can easily be worked around using the DataResource technique from a previous post. Here's how you would use this technique for max/min integer validation.

First create the rule class:
public class IntValidationRule : ValidationRule
{
    public int Max { get; set; }
    public int Min { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        try
        {
            int i = Convert.ToInt32(value);
            return (i < Min || i > Max) ?
                new ValidationResult(false, "int out of range") :
                new ValidationResult(true, null);
        }
        catch (FormatException fe)
        {
            return new ValidationResult(false, fe.Message);
        }
    }
}
...the DataResources and the associated bindings should then simply be set up like this:
<Window.Resources>
    <my:DataResource x:Key="max" BindingTarget="{Binding Max}"/>
    <my:DataResource x:Key="min" BindingTarget="{Binding Min}"/>
</Window.Resources>

<TextBox>
    <TextBox.Text>
        <Binding UpdateSourceTrigger="PropertyChanged" Path="Value">
            <Binding.ValidationRules>
                <my:IntValidationRule 
                    ValidatesOnTargetUpdated="True" 
                    Min="{my:DataResourceBinding DataResource={StaticResource min}}"
                    Max="{my:DataResourceBinding DataResource={StaticResource max}}">
                </my:IntValidationRule>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>



DataResource.cs
Download sample app with source code



2 comments:

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Pamorale said...

Hi... I'm trying to set a property through binding similar as you did. I have a many to many relationship like this in 3 tables:
A-->AB<--B,
THe AB table has a value atribute wich I want to validate.
The B table has a property name "type" and it could be "Integer", "Mail", "DateTime", "Boolean", etc. I like to use that property to perform the validation. How can I achieve this goal????
THanks in advance...