WPF ValidationTule 绑定参数问题

WPF ValidationTule with binding parameter problem

我需要将绑定值传递给我的验证规则。这是 XAML 代码:

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

代码隐藏:

    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); }
    }
}

基本上我无法将所需的值输入我的 TinoInterno 属性。如果我硬编码这样的值:

<local:Wrapper TipoInterno="TEST" />

属性 已正确定价。在第一种情况下,我需要使用 elementName txtTipo 传递 属性 控件内容。 怎么了?

您应该在 ValidationRule:

中获取 Wrapper 实例的 TipoInterno 的值
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
    string s = Wrapper.TipoInterno;
    return ...;
}

然后您可以使用 x:Reference:

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