开发者

How to pass ValidationRule class's properties value at run time in WPF?

I have ValidationRule Class for Discount Percentage Validation (as below)

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

In XAML we use this ValiationRule class as below and set Min and Max Properties in ValidationRules Tag

<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>
            <loc开发者_如何转开发al:DiscountPerRule Max="100" Min="0"/>
        </Binding.ValidationRules>
    </Binding>
</TextBox>

So, How to assign/Reassign Min and Max value at runtime(Programaticaly) in C# code


The easiest way would be to name the validation rule in your XAML:

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

And then use code like this in your code-behind to alter it:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜