我正在使用以下WPF文档示例:How to: Implement Validation with the DataGrid Control
这个例子组装后效果很好;然而,有一个陷阱。验证技术不会检查加载时的有效值。我有一个场景,需要根据db检查初始加载的值。在用户与视图交互之前,不会调用示例中的Validate函数。如何克服这一挑战?
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
Course course = (value as BindingGroup).Items[0] as Course;
// Some condition
}
答案 0 :(得分:1)
T
的{{1}}类型IEnumerable<T>
应该用作ItemsSource
的{{1}}来实现DataGrid
接口。然后,只需从INotifyDataErrorInfo
方法返回错误。
这是一个基本的例子。
<强>型号:强>
GetErrors
查看:强>
public class Company : INotifyDataErrorInfo
{
private readonly Dictionary<string, string> _validationErrors = new Dictionary<string, string>();
public Company()
{
//validate immediately:
ValidateName();
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
ValidateName();
}
}
public void ValidateName()
{
if (string.IsNullOrEmpty(_name))
_validationErrors["Name"] = "cannot be empty...";
else
_validationErrors.Remove("Name");
RaiseErrorsChanged("Name");
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private void RaiseErrorsChanged(string propertyName)
{
if (ErrorsChanged != null)
ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
public System.Collections.IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName) || !_validationErrors.ContainsKey(propertyName))
return null;
return new List<string>(1) { _validationErrors[propertyName] };
}
public bool HasErrors
{
get { return _validationErrors.Count > 0; }
}
}
您可以在此处详细了解界面以及WPF中数据验证的工作原理:https://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/