2013-07-30 83 views
1

我正在使用IDataErrorInfo繼承業務對象進行驗證。如何清除WPF IDataErrorInfo驗證錯誤

public string UserId { get; set; } 

public string this[string columnName] 
    { 
     get 
     { 
      string result = null; 

      if (columnName == "UserId") 
      { 
       if (string.IsNullOrEmpty(UserId)) 
        result = "Please enter User Id"; 
      } 
     } 
    } 

我想清除所有的驗證錯誤,當我點擊菜單上的按鈕 - 如 - 登出。

窗口使「登錄」面板可見,但前面板的驗證錯誤標記仍顯示在當前登錄面板中。

我嘗試了所有的選項指定NULL的datacontext,新鮮實體對象......但沒有運氣

我感謝你的幫助。

回答

2

使用IDataErrorInfo接口是一種錯誤優先類型的方法。這意味着你會看到錯誤,直到它們被清除。您可以看到索引器上沒有setter。

原始IDataErrorInfo接口本身並不過分有用,因爲它一次只處理一個錯誤。我增加了以下領域爲我BaseDataType類:

protected ObservableCollection<string> errors = new ObservableCollection<string>(); 

在我的實際數據類,我有以下特性:

public override ObservableCollection<string> Errors 
{ 
    get 
    { 
     errors = new ObservableCollection<string>(); 
     errors.AddUniqueIfNotEmpty(this["Property1"]); 
     errors.AddUniqueIfNotEmpty(this["Property2"]); 
     errors.AddUniqueIfNotEmpty(this["PropertyN"]); 
     return errors; 
    } 
} 

AddUniqueIfNotEmpty方法是一個擴展方法,我認爲是不言自明。此屬性可以多次調用索引器,並將所有結果編譯爲一個ObservableCollection<string>集合,以準備在UI中顯示。當需要更新Property1,Property2PropertyN以使其工作時,您需要撥打INotifyPropertyChanged.PropertyChanged事件的名稱Errors

你可以這樣做,但是當你想清除錯誤時,爲你添加一個setter來傳入一個空的集合或字符串。