【问题标题】:WPF INotifyErrorInfo Validation.Error Event Not RaisingWPF INotifyErrorInfo Validation.Error 事件未引发
【发布时间】:2017-01-16 23:46:45
【问题描述】:

我遇到了一个奇怪的问题。尽管正确设置了所有内容,但 Validation.Error 不会被触发。

详情如下:

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

设置 HeaderedItemsControl 的 ItemsSource 的代码(VB.Net):

hicLateComers.ItemsSource = _LateComersViewModels

_LateComersViewModels 是 ObservableCollection(Of 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 属性。

【问题讨论】:

    标签: wpf vb.net validation


    【解决方案1】:

    由于 Validation.Error 是一个附加事件,您可以在 HeaderedItemsControl 上连接事件处理程序:

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

    结果应该几乎相同,因为您可以在事件处理程序中轻松访问 TextBox 和 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
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      相关资源
      最近更新 更多