我有一个自定义文本框组件(继承自 system.windows.forms.textbox),它是在 vb.net(2005)中创建的,用于处理数字数据的输入。它运作良好。
如果数字没有改变,我想禁止触发验证和验证事件。如果用户在表单和文本框中的选项卡中切换,则会触发验证/验证事件。
我在想文本框可以缓存该值并将其与文本属性中列出的内容进行比较。如果它们不同,那么我希望触发验证/验证事件。如果它们相同,则不会触发任何内容。
我似乎无法弄清楚如何抑制事件。我尝试过覆盖 OnValidating 事件。那没有用。
有任何想法吗?
更新:
这是自定义文本框类。这个想法是我想在验证事件上缓存文本框的值。一旦缓存了该值,下次用户通过该框进行选项卡时,验证事件将检查 _Cache 是否与 .Text 不同。如果是这样,那是我想将验证事件引发到父表单(以及验证事件)的时候。如果 _cache 相同,那么我不想将事件引发到表单。本质上,文本框与常规文本框的工作方式相同,只是验证和验证方法仅在文本更改时才被提升到表单中。
Public Class CustomTextBox
#Region "Class Level Variables"
Private _FirstClickCompleted As Boolean = False 'used to indicate that all of the text should be highlighted when the user box is clicked - only when the control has had focus shifted to it
Private _CachedValue As String = String.Empty
#End Region
#Region "Overridden methods"
Protected Overrides Sub OnClick(ByVal e As System.EventArgs)
'check to see if the control has recently gained focus, if it has then allow the first click to highlight all of the text
If Not _FirstClickCompleted Then
Me.SelectAll() 'select all the text when the user clicks a mouse on it...
_FirstClickCompleted = True
End If
MyBase.OnClick(e)
End Sub
Protected Overrides Sub OnLostFocus(ByVal e As System.EventArgs)
_FirstClickCompleted = False 'reset the first click flag so that if the user clicks the control again the text will be highlighted
MyBase.OnLostFocus(e)
End Sub
Protected Overrides Sub OnValidating(ByVal e As System.ComponentModel.CancelEventArgs)
If String.Compare(_CachedValue, Me.Text) <> 0 Then
MyBase.OnValidating(e)
End If
End Sub
Protected Overrides Sub OnValidated(ByVal e As System.EventArgs)
_CachedValue = Me.Text
MyBase.OnValidated(e)
End Sub
#End Region
End Class
更新 2:
感谢xpda,解决方案很简单(简单到我不明白:))。将 OnValidating 和 OnValidated 替换为(还需要一个布尔值来记录状态):
Protected Overrides Sub OnValidating(ByVal e As System.ComponentModel.CancelEventArgs)
If String.Compare(_CachedValue, Me.Text) <> 0 Then
_ValidatingEventRaised = True
MyBase.OnValidating(e)
End If
End Sub
Protected Overrides Sub OnValidated(ByVal e As System.EventArgs)
If Not _ValidatingEventRaised Then Return
_CachedValue = Me.Text
_ValidatingEventRaised = False
MyBase.OnValidated(e)
End Sub