开发过程中会遇到一些数据录入的地方,录入过程中会涉及到数据的验证问题。 WPF中有一种容器,叫做装饰器。使用装饰器,和Binding中的ValidationRules进行数据验证,和MVVM模式,我觉得效果非常好。 前台的XAML中有这样一个控件: TextBox Height = 24 Width = 222 Binding Path = PanelCount UpdateSourceTrigger = Prope
开发过程中会遇到一些数据录入的地方,录入过程中会涉及到数据的验证问题。
WPF中有一种容器,叫做装饰器。使用装饰器,和Binding中的ValidationRules进行数据验证,和MVVM模式,我觉得效果非常好。
前台的XAML中有这样一个控件:
<TextBox Height="24" Width="222"> <Binding Path="PanelCount" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <VM:AgeValidation Max="30" Min="20" /> </Binding.ValidationRules> </Binding> <Validation.ErrorTemplate> <ControlTemplate> <Border CornerRadius="3" BorderBrush="Red" BorderThickness="1"> <StackPanel> <AdornedElementPlaceholder/> <TextBlock Text="年龄只能在20 - 30之间" Foreground="Red"> <TextBlock.Effect> <DropShadowEffect Opacity="0.6" ShadowDepth="3" Color="Black"/> </TextBlock.Effect> </TextBlock> </StackPanel> </Border> </ControlTemplate> </Validation.ErrorTemplate> </TextBox>
上面的代码中有这样一行 AgeValidation就是用来给TextBox做验证的类,有两个参数MAX和MIN不用说,一个对应的文本框最大值,一个对应文本框最小值,所以,这个TextBox只能输入20到30之间的数,输入其他的会提示错误,这就是我要的数据验证方式。因为UpdateSourceTrigger="PropertyChanged"所以,在没输入一个字符的时候就会做一次验证。这样,就得到了即时的验证消息。
我们需要AgeValidation类,用来判断输入的值是否是合法的值。
public class AgeValidation : ValidationRule
{
private int _min;
private int _max;
public AgeValidation()
{
}
public int Min
{
get { return _min; }
set { _min = value; }
}
public int Max
{
get { return _max; }
set { _max = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int age = 0;
try
{
if (((string)value).Length > 0)
age = Int32.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters or " + e.Message);
}
if ((age < Min) || (age > Max))
{
return new ValidationResult(false, null);
//下面的return返回的参数在页面中可以通过TextBox的(ValidationErrors)[0].ErrorContent获取
//return new ValidationResult(false, string.Format("年龄只能在{0}-{1}之间.", _min, _max));
}
else
{
return new ValidationResult(true, null);
}
}
}
下面上图:
输入正确的值:

输入了错误的值:

原文地址:http://www.luacloud.com/2011/05/31/849/