WPF DependencyProperty Validation Binding fails

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EARNEST
    New Member
    • Feb 2010
    • 128

    WPF DependencyProperty Validation Binding fails

    0 down vote favorite


    I am trying to create a validation rule for a given control (in this scenario, it is the TextBox).

    I am not able to obtain a successful Binding to the property of an object, although appropriate steps were taken: ValidationRule and DepedencyProper ty are taken advantage of.

    Kindly find code below. A side note is that "Is Required" in the custom Validation class is always False, unless I explicitly set the value in the XAML (no Binding, as per "Is Ranged" parameter).

    Alternative is to use IDataErrorInfo interface, but I would like to stick to the ValidationRules .

    Any tips and suggestions are appreciated.

    Thank you in advance :)


    XAML Code:

    Code:
    <TextBox Style="{StaticResource ValidationError}" LostFocus="ForceValidationCheck"
             Visibility="{Binding Type, Converter={StaticResource Visibility}, ConverterParameter='Number'}"
             IsEnabled="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource IsEnabled}}">
        <TextBox.Text>
            <Binding Path="Value">
                <Binding.ValidationRules>
                    <validation:NumericValidation>
                        <validation:NumericValidation.Dependency>
                            <validation:NumericDependency IsRequired="{Binding Path=IsRequired}" IsRanged="True" Min="5"/>
                        </validation:NumericValidation.Dependency>
                    </validation:NumericValidation>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
    Validation Class:

    Code:
    public NumericDependency Dependency { get; set; }
    
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        isRequired = Dependency.IsRequired;
    }
    Validation Dependency Class:

    Code:
    public static readonly DependencyProperty IsRequiredProperty =
            DependencyProperty.Register("IsRequired", typeof(bool), typeof(NumericDependency), new UIPropertyMetadata(default(bool)));
    
    public bool IsRequired
    {
        get
        {
            return (bool) GetValue(IsRequiredProperty);
        }
        set
        {
            SetValue(IsRequiredProperty, value);
        }
    }
Working...