只是爲了表明這一點利用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