2017-01-16 76 views
0

我遇到了一個奇怪的問題。儘管設置正確,但Validation.Error並未被觸發。WPF INotifyErrorInfo Validation.Error事件不會上升

下面是詳細信息:

<DataTemplate x:Key="dtLateComers"> 
    <TextBox Text="{Binding ParticipantTag, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True, NotifyOnSourceUpdated=True}" Validation.Error="Validation_Error" > 
</DataTemplate> 

後面的代碼(VB.Net)設置HeaderedItemsControl的的ItemsSource:

hicLateComers.ItemsSource = _LateComersViewModels 

_LateComersViewModels是的ObservableCollection(中ParticipantViewModel)ParticipantViewMode的

實施:

Public Class ParticipantViewModel 
Implements INotifyPropertyChanged, IDataErrorInfo 

Private _ParticipantTag As String = "" 

Public Property ParticipantTag() As String 
    Get 
     Return _ParticipantTag 
    End Get 
    Set(ByVal value As String) 
     _ParticipantTag = value 
     _ParticipantTag= _ParticipantTag.ToUpper  

     NotifyPropertyChanged("ParticipantTag") 
    End Set 
End Property 

Public ReadOnly Property Item(byVal columnName As String) As String Implements IDataErrorInfo.Item 
    Get 
     Dim errorString As String = String.Empty 

     If columnName.Equals("ParticipantTag") Then 

      If not ParticipantValidationManager.IsValidKeypadTag(_ParticipantTag, True) then 
       errorString = "Incorrect entry. Please try again." 
      End If 
     End If 

     Return errorString 
    End Get 
End Property 

Public ReadOnly Property [Error] As String Implements IDataErrorInfo.Error 
    Get 
     Throw New NotImplementedException() 
    End Get 
End Property 

End Class 

問題 當我設置ItemSource屬性(如代碼中所述)時,Item索引被調用多次,因爲_LaterComersViewModels中有項目。驗證工作,因此我得到TextBox旁邊的紅色圓圈。但是,直到我開始在文本框中輸入時,Validation_Error纔會被觸發。在TextBox中鍵入更改屬性綁定到它並驗證它。基於驗證Validation.Error事件被引發,並由應用程序處理。在該事件處理程序中,我保留了一些錯誤。

所以,問題是,爲什麼Validation.Error沒有得到當一個/多個項目在最初的數據綁定在驗證規則失敗長大的嗎?儘管通過在TextBox中輸入內容來改變屬性,它確實會被提升。

隨意分享任何想法,假設或解決方案。任何類型的幫助將不勝感激。謝謝。

附註:我不使用數據模板一個簡單的C#應用​​程序。在該應用程序中,Validation.Error事件在開始時和完成屬性更改時得到完美提升。雖然在該應用程序中,Model綁定到Grid的DataContext屬性。

回答

1

由於Validation.Error是一個附加的事件,你可以掛鉤的事件處理程序上HeaderedItemsControl:

<HeaderedItemsControl x:Name="hicLateComers" ItemTemplate="{StaticResource dtLateComers}" Validation.Error="Validation_Error" /> 

結果應該是幾乎相同的,因爲你可以很容易地訪問這兩個文本框和ParticipantViewModel對象在事件處理程序:

Private Sub Validation_Error(sender As Object, e As ValidationErrorEventArgs) 
    Dim textBox = CType(e.OriginalSource, TextBox) 
    Dim participant = CType(textBox.DataContext, ParticipantViewModel) 

    '... 
End Sub