只是为了说明我是如何使用IDataErrorInfo...
我在视图绑定属性的每个设置器中调用了一个名为 OnDataUpdated() 的新方法,例如:
private string username;
public string Username
{
get { return username; }
set
{
username = value;
OnDataUpdated();
}
}
private string password;
public string Password
{
get { return password; }
set
{
password = value;
OnDataUpdated();
}
}
然后在OnDataUpdated() 内部将私有字段布尔值标记为true,表示数据首次更改(FormType 仅对我的业务案例是必需的):
private void OnDataUpdated()
{
dataChanged = true;
// .. Any other universal RaisePropertyChanged() events you may want to call to get your UI into sync. Eg. RaisePropertyChanged(() => CanConfirm);
}
然后在我的IDataErrorInfo indexer 属性中,我执行以下操作(我将其拆分,因此也可以手动调用 'ValidForm()' 来执行表单验证。
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Username")
{
// If other payment amounts have fully paid for balance, and cash amount has been entered, deny
if (!ValidForm(FormType.Step1, columnName))
result = "Please enter the username field.";
}
else if (columnName == "Password")
{
if (!ValidForm(FormType.Step1, columnName))
result = "Please enter the password field.";
}
return result;
}
}
/// <summary>
/// Test if valid form.
/// </summary>
/// <param name="formType">Specify which form we should validate.</param>
/// <param name="columnName">If ommitted, entire form will be validated.</param>
/// <returns></returns>
private bool ValidForm(FormType formType, string columnName = null)
{
// This field is used to denote when data has changed on the form.
// If data has changed, we know we can activate any form validation.
// We do not activate the form validation until after a user has typed
// something in at least.
if (!dataChanged) return true;
var errors = false;
if (formType == FormType.Step1 && ((string.IsNullOrEmpty(columnName) || columnName == "Username") && string.IsNullOrEmpty(Username)))
errors = true;
if (formType == FormType.Step1 && ((string.IsNullOrEmpty(columnName) || columnName == "Password") && string.IsNullOrEmpty(Password)))
errors = true;
return !errors;
}
效果很好。现在我只有在用户编辑表单后才会出现验证样式。
如果您想锦上添花,可以在OnDataUpdated() 方法中的RaisePropertyChanged(() => CanConfirm); 中发表评论,并将其绑定到您的确认按钮IsEnabled={Binding CanConfirm} 和相关属性:
/// <summary>
/// Can the user confirm step 1?
/// </summary>
public bool CanConfirm
{
get { return ValidForm(FormType.Step1); }
}
只有当您的表单也有效时,您的按钮才会启用。 :)
享受吧!祝 WPF 这个庞然大物好运。