验证之 ValidationRule 简单Demo
验证用户是否年满18+
public class AgeRule : ValidationRule { private Double limitAge = 18; public Double LimitAge { get { return limitAge; } set { limitAge = value; } } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { Double age = (Double)value ; if (limitAge < age ) { return new ValidationResult(true, null); } else { return new ValidationResult(false,"年龄范围错误"); } } }
页面使用:
<StackPanel> <Slider x:Name="age" Minimum="0" Maximum="100" /> <Label > <Label.Content> <Binding ElementName="age" Path="Value" Mode="OneWay" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <local:AgeRule ValidatesOnTargetUpdated="True"/> </Binding.ValidationRules> </Binding> </Label.Content> </Label> </StackPanel>
效果一:
效果二: