正如您可能從標題中看到的那樣,我正要問以前曾被問過很多次的問題。但是,在閱讀所有這些其他問題後,我仍然無法找到解決我的問題的體面解決方案。驗證失敗時禁用保存按鈕
我有一個基本的驗證模型類:
partial class Player : IDataErrorInfo
{
public bool CanSave { get; set; }
public string this[string columnName]
{
get
{
string result = null;
if (columnName == "Firstname")
{
if (String.IsNullOrWhiteSpace(Firstname))
{
result = "Geef een voornaam in";
}
}
if (columnName == "Lastname")
{
if (String.IsNullOrWhiteSpace(Lastname))
{
result = "Geef een familienaam in";
}
}
if (columnName == "Email")
{
try
{
MailAddress email = new MailAddress(Email);
}
catch (FormatException)
{
result = "Geef een geldig e-mailadres in";
}
}
if (columnName == "Birthdate")
{
if (Birthdate.Value.Date >= DateTime.Now.Date)
{
result = "Geef een geldige geboortedatum in";
}
}
CanSave = true; // this line is wrong
return result;
}
}
public string Error { get { throw new NotImplementedException();} }
}
此驗證每次完成屬性的變化(所以每次用戶鍵入的文本字符):
<TextBox Text="{Binding CurrentPlayer.Firstname, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="137" IsEnabled="{Binding Editing}" Grid.Row="1"/>
該作品完善。驗證發生(綁定的PropertyChanged
代碼在CurrentPlayer屬性(它是Player的對象)的VM中完成)。
我現在想要做的是在驗證失敗時禁用保存按鈕。
首先,最簡單的解決方案,似乎在這個線程中發現:
Enable Disable save button during Validation using IDataErrorInfo
- 如果我想跟進接受的解決方案,我不得不寫我 驗證代碼的兩倍,如我不能簡單地使用索引器。編寫 雙代碼是絕對不是我想要的,所以這不是我的問題 的解決方案。
- 該線程的第二個答案聽起來非常有希望作爲首先, 但問題是我有多個字段必須驗證 。這樣,所有東西都依賴於最後選中的屬性 (所以如果該字段填寫正確,
CanSave
將爲真,即使 儘管還有其他字段仍然無效)。
我發現的另一個解決方案是使用ErrorCount
屬性。但是,當我在每次房產更改時(以及每個輸入的字符)驗證時,這是不可能的 - 我怎麼知道何時增加/減少ErrorCount
?
解決此問題的最佳方法是什麼?
感謝
避免編寫像這樣的所有驗證類,這很受歡迎,因爲它很受歡迎。值得注意的是,如果列的名稱映射到具有錯誤結果的塊,那麼可以使用委託函數的映射;產生所有'如果'是不必要的。但是讓我們假設你要使用它們,你在if(A)中做了一個if(B)',這樣你就可以做一個if(A && B)'。如果只在'if'中執行一條語句,則不必鍵入'{'和'}'字符。通過使用地圖,這個例子可以在~20行而不是~50行;加倍你的發展。 –