只是为了表明这一点利用IDataErrorInfo
我如何处理......
我把调用一个在我看来绑定属性的每个setter方法称为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
索引器属性中,我执行以下操作(我将其分开,以便可以手动调用'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;
}
工程很漂亮。现在我只有在用户编辑表单后才会出现验证样式。
如果你想在蛋糕上一些额外的结冰,你可以在我的RaisePropertyChanged(() => CanConfirm);
在OnDataUpdated()
方法发表意见,并结合,为您的确认按钮IsEnabled={Binding CanConfirm}
与关联的属性:
/// <summary>
/// Can the user confirm step 1?
/// </summary>
public bool CanConfirm
{
get { return ValidForm(FormType.Step1); }
}
和您的按钮才可当你的表单也有效时启用。 :)
享受!并且与WPF这个庞然大物一样好运。
你有没有为这个Brian制定出最好的方法? :\ – GONeale 2012-08-16 01:17:31