为进行校验,必须准备一个RangeValidationRule类,该类继承自ValidationRule
该类实现如下:
class RangeValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
double d;
if (double.TryParse(value.ToString(), out d))
{
if (d >= && d <= )
{
return new ValidationResult(true, null);
}
}
return new ValidationResult(false, "Validation Failed");
}
}
界面上仍2个控件,相应的XAML
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="84,63,0,0" Name="textBox1" VerticalAlignment="Top" Width="336" IsEnabled="True"/>
<Slider Name="slider1" Height="23" HorizontalAlignment="Left" Margin="84,125,0,0" VerticalAlignment="Top" Width="336" Maximum="110" Minimum="-1"/>
</Grid>
1.基本验证
//1.基本验证
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
binding.ValidationRules.Add(new RangeValidationRule());
this.textBox1.SetBinding(TextBox.TextProperty, binding);
2.数据源验证
//2.验证source
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
binding.ValidationRules.Add(new RangeValidationRule()
{
ValidatesOnTargetUpdated = true
});
binding.NotifyOnValidationError = true;
this.textBox1.SetBinding(TextBox.TextProperty, binding);
3.添加路由事件
this.textBox1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler((sender, e) =>
{
if (Validation.GetErrors(this.textBox1).Count > )
{
this.textBox1.ToolTip = Validation.GetErrors(this.textBox1)[].ErrorContent.ToString();
}
}));