WPF中 Datagrid 绑定到数据库后如何对用户输入的数据进行验证?

如题所述

第1个回答  推荐于2016-03-21
使用ValidationRule。以下为示例:

Binding testBinding = new Binding();
testBinding.ValidationRules.Add(new IPv4ValidationRule());//添加验证,根据数据类型添加不一样的验证类
testBinding.Mode = BindingMode.TwoWay;
testBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
testBinding.Path = new PropertyPath("[" + myTextBox.Name + "].Permit");//绑定源路径
testBinding.Source = dic; //绑定源,
myTextBox.SetBinding(TextBox.TextProperty ,testBinding );//绑定目标属性
数据验证也是加的数据验证类继承ValidationRule。

public class IPv4ValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var str = value as string;
if (String.IsNullOrEmpty(str))
{
MessageBox.Show("请输入日期。");
//return new ValidationResult(false,
// "Please enter an IP Address.");
}
return new ValidationResult(true, null);
}
}本回答被提问者采纳
相似回答