Search code examples
wpfdependency-propertiesvalidationrules

WPF ValidationTule with binding parameter problem


I need to pass a bind value to my validation rule. This is the XAML code:

    <Label Grid.Column="11" Content="Default" Style="{StaticResource labelStyle2}" x:Name="txtTipo" />
<TextBox Grid.Column="12" Style="{StaticResource txtDataStyle1}" Width="100" TextChanged="Data_TextChanged">
    <Binding Path="ConfigObject.Edit.Default" UpdateSourceTrigger="Default">
        <Binding.ValidationRules>
            <local:GenericValidationRule>
                <local:GenericValidationRule.Wrapper>
                    <local:Wrapper TipoInterno="{Binding ElementName=txtTipo, Path=Content}"/>
                </local:GenericValidationRule.Wrapper>
            </local:GenericValidationRule>
        </Binding.ValidationRules>
    </Binding>
</TextBox>

Codebehind:

    public class GenericValidationRule : ValidationRule
{
    public Wrapper Wrapper { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var xx = Wrapper.TipoInternoProperty;   //TEST
        return new ValidationResult(is_valid, error_context);
    }
}

public class Wrapper : DependencyObject
{
    public static readonly DependencyProperty TipoInternoProperty = DependencyProperty.Register("TipoInterno", typeof(string), typeof(Wrapper), new PropertyMetadata(string.Empty));
    public string TipoInterno
    {
        get { return (string)GetValue(TipoInternoProperty); }
        set { SetValue(TipoInternoProperty, value); }
    }
}

Basically I cannot get the required value into my TinoInterno property. If I hardcode a value such:

<local:Wrapper TipoInterno="TEST" />

the property is correctly valorized. In the first case I need to pass the property Content of control with elementName txtTipo. What's wrong?


Solution

  • You should get the value of the TipoInterno of the Wrapper instance in the ValidationRule:

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        string s = Wrapper.TipoInterno;
        return ...;
    }
    

    You could then bind using an x:Reference:

    <local:Wrapper TipoInterno="{Binding Path=Content, Source={x:Reference txtTipo}}"/>