我有一個DataGrid綁定到「Customer」類的ObservableCollection,實現了IDataErrorInfo。一個Customer類的屬性是int
,在我IDataErrorInfo的執行我檢查,這是一個有效的範圍內,e.g.:-WPF數據網格驗證不一致性
public class Customer : IDataErrorInfo
{
public int PercentDiscount { get; set; }
... other properties & methods removed for clarity
public string this[columnName]
{
get
{
if (PercentDiscount < 0 || PercentDiscount > 10)
return "Percent Discount is invalid";
}
}
}
在我的XAML我的代碼隱藏處理幾個事件。在PreparingCellForEdit
事件中,我存儲對行的引用被編輯: -
private void DataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
{
_rowBeingEdited = e.Row;
}
然後在RowEditEnding
事件中,我採取了一些行動,如果該行處於無效狀態(在我的情況我回復客戶屬性恢復他們以前的「好」的值): -
private void DataGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
if (_rowBeingEdited != null)
{
var errors = Validation.GetErrors(_rowBeingEdited);
if (errors.Count > 0)
{
.. do something
}
}
}
這工作正常,如果用戶輸入失敗我的驗證規則的數值,但如果用戶輸入一個非數字值,那麼RowEditEnding
事件從未火災該單元保持編輯狀態。我認爲這是因爲WPF無法將非數字值綁定到int
屬性。有什麼辦法可以檢測/處理這種情況嗎?
最後的手段是將PercentDiscount
屬性更改爲字符串,但我試圖避免沿着這條路線走下去。
編輯 - 我剛剛發現,我可以用CellEditEnding
事件,而不是RowEditEnding
成功地處理這兩種類型的錯誤。雖然出現了一個新問題 - 如果我輸入一個無效值到單元格中,然後按輸入,底層屬性不會更新,因此當CellEditEnding觸發Validation.GetErrors
爲空時。最終的結果是該行離開編輯模式,但仍在紅色邊框的單元格中顯示無效值。任何想法現在發生了什麼?