如何在WPF中运行时传递ValidationRule类的属性值?

时间:2011-06-28 10:54:32

标签: wpf binding

我有折扣百分比验证的ValidationRule类(如下所示)

public class DiscountPerRule : ValidationRule
{
    public float Min { get; set; }

    public float Max { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        float _prm = 0f;
        try
        {
            if (value.ToString().Length > 0)
            {
                _prm = float.Parse(value.ToString());
            }
        }
        catch
        {
            return new ValidationResult(false, "Illegal Characters, Please Enter Numaric Value");
        }
        if ((_prm < Min) || (_prm > Max))
        {
            return new ValidationResult(false, String.Format("Please enter value in the Range: {0} - {1}.", this.Min, this.Max));
        }
        return new ValidationResult(true, null);
    }
}

在XAML中,我们使用如下的ValiationRule类,并在ValidationRules标记中设置最小和最大属性

<TextBox x:Name="txtDisPer" Width="108" HorizontalAlignment="Center" VerticalAlignment="Center" Validation.Error="txtDisPer_Error" >
    <Binding Path="Rate" UpdateSourceTrigger="PropertyChanged" ValidatesOnExceptions="True" ValidatesOnDataErrors="True" NotifyOnValidationError="True" Mode="TwoWay" NotifyOnSourceUpdated="True" NotifyOnTargetUpdated="True">
        <Binding.ValidationRules>
            <local:DiscountPerRule Max="100" Min="0"/>
        </Binding.ValidationRules>
    </Binding>
</TextBox>

那么,如何在C#代码中分配/重新分配运行时的最小值和最大值(Programaticaly)

1 个答案:

答案 0 :(得分:1)

最简单的方法是在XAML中命名验证规则:

<local:DiscountPerRule x:Name="discountPerRule" Max="100" Min="0"/>

然后在代码隐藏中使用这样的代码来改变它:

discountPerRule.Min = 10;
discountPerRule.Max = 50;