2017-01-16 74 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