WPF中 Datagrid 绑定到数据库后如何对用户输入的数据进行验证?
展开全部
使用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);
}
}
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);
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询