【问题标题】:WPF ValidationTule with binding parameter problem具有绑定参数问题的 WPF ValidationTule
【发布时间】:2019-03-23 06:59:48
【问题描述】:

我需要将绑定值传递给我的验证规则。这是 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 传递控件的属性 Content。 怎么了?

【问题讨论】:

    标签: wpf dependency-properties validationrules


    【解决方案1】:

    您应该在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}}"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-18
      • 2014-05-25
      • 1970-01-01
      • 2010-12-09
      相关资源
      最近更新 更多