自定义验证规则WPF和项控件

本文关键字:控件 WPF 验证 规则 自定义 | 更新日期: 2023-09-27 18:23:51

在绑定到数据源的ItemsControl中,我试图使用接受参数的自定义验证规则来验证TextBox,下面是验证规则的代码。

public class RatioValidation : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (!String.IsNullOrEmpty(Maturity.MaturityValue) && Helper.IsDateInCorrectFormat(Maturity.MaturityValue))
        {
            String strVal = Convert.ToString(value);
            Double ratio = 0;
            Boolean isValid = Double.TryParse(strVal, out ratio);
            if (isValid)
            {
                if (ratio <= 0)
                    return new ValidationResult(false, "Please enter a valid ratio!");
                else return new ValidationResult(true, null);
            }
            return new ValidationResult(false, "Please enter a valid ratio!");
        }
        else return new ValidationResult(true, null);           
    }
    private MaturityDependencyForValidation _maturity;
    public MaturityDependencyForValidation Maturity
    {
        get { return _maturity; }
        set { _maturity = value; }
    }
}
public class MaturityDependencyForValidation : DependencyObject
{
    public String MaturityValue
    {
        get { return (String)GetValue(MaturityValueProperty); }
        set { SetValue(MaturityValueProperty, value); }
    }
    public static readonly DependencyProperty MaturityValueProperty =
        DependencyProperty.Register("MaturityValue", typeof(String), typeof(MaturityDependencyForValidation), new UIPropertyMetadata(null));
}

然后像下面这样使用,

<TextBox Grid.Row="1" Grid.Column="2"  Name="txtRatio" BorderThickness="0" Width="148" Tag="{Binding StrMaturity, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.Text>
        <Binding Path="Ratio" Mode="TwoWay"  UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <leg:RatioValidation ValidatesOnTargetUpdated="True">
                    <leg:RatioValidation.Maturity>
                         <leg:MaturityDependencyForValidation MaturityValue="{Binding txtMaturity}"/>
                    </leg:RatioValidation.Maturity>
                </leg:RatioValidation>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

我在输出窗口中得到一个异常:

找不到目标元素的管理FrameworkElement或FrameworkContentElement。BindingExpression:Path=txtMaturity;DataItem=null;目标元素为"MaturityDependencyForValidation"(哈希代码=63478077);目标属性为"Maturity"(类型为"String")

RatioValidation规则中,Maturity的值从未从数据绑定中绑定。我需要这个值来进行数据绑定。请帮忙。

自定义验证规则WPF和项控件

没有DataContext,因为周围的对象,绑定至少不是DependencyObjects,您的选择有些有限,它应该类似于在数组中绑定时发生的情况,也可以看到这个答案。