WPF ValidationRule有效性验证——验证textbox数据范围
textbox有效性验证,前端引入如下:
<TextBox> <TextBox.Resources> <sys:Int32 x:Key="NumericRangeMinValue">0</sys:Int32> </TextBox.Resources> <TextBox.Text> <Binding Path="Name" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:NumericRangeValidationRule MinValue="{StaticResource NumericRangeMinValue}" MaxValue="100" /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox>
注意上述为textbox添加了一个资源,其是不必要的,可以将MinValue直接在加粗行设置即可。
添加的ValidationRule规则:
public class NumericRangeValidationRule : ValidationRule { public int MinValue { get; set; } public int MaxValue { get; set; } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (int.TryParse(value?.ToString(), out int number)) { if (number < MinValue || number > MaxValue) { return new ValidationResult(false, $"请输入 {MinValue} 到 {MaxValue} 之间的数字"); } } return ValidationResult.ValidResult; } }
*****有道无术,术尚可求;有术无道,止于术。*****