我有一个TextBox绑定到DateTime使用实现Convert和ConvertBack的转换器。 UpdateSourceTrigger设置为PropertyChanged,以便在用户键入时完成验证。这是问题所在:
这是不可取的,因为文本可以更改为完整日期,而用户只键入了部分日期。如何阻止UI执行此操作?请注意,由于此功能,从.NET 3.5升级到4.0后,这只会成为一个问题:
http://karlshifflett.wordpress.com/2009/05/27/wpf-4-0-data-binding-change-great-feature/
感谢您的帮助!
答案 0 :(得分:1)
您可以使用Data Validation,它允许您在属性获取类型值之前检查键入的值是否满足特定条件(例如正则表达式) - >只有满足条件才会调用转换器。
另一个建议是,如果键入的值是DateTime,则通过正则表达式检入Converter,并且只有匹配时才转换它。
答案 1 :(得分:0)
试试这个:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'Limit the length of the number that can be entered to 12 (This is arbitrary)
If Len(TextBox1.Text) > 12 Then
KeyAscii = 0
Exit Sub
End If
If KeyAscii < 32 Then
Exit Sub ' let it go, it is a control char like backspace
End If
If InStr("0123456789.", Chr$(KeyAscii)) > 0 Then
If InStr(TextBox1.Text, ".") > 0 Then
If Chr$(KeyAscii) = "." Then
KeyAscii = 0 ' do not allow more than one decimal point
Beep
MsgBox "Only 2 decimal places to be allowed", vbCritical
Exit Sub
ElseIf Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 2 Then
KeyAscii = 0 ' do not allow more than 2 digits past decimal point
Beep
MsgBox "Only 2 decimal places to be allowed", vbCritical
Exit Sub
End If
End If
Else
Beep
KeyAscii = 0
End If
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, "$") + 1)) >= 1 Or KeyAscii < 32 Then
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 2 Then
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = Format(TextBox1.Text, "$#,###")
Else
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = TextBox1.Text
End If
ElseIf Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, "$") + 1)) >= 0 Or KeyAscii < 32 Then
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 2 Then
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = Format(TextBox1.Text, "$#,###")
Else
If KeyAscii < 32 Then Beep: Exit Sub
TextBox1.Text = ""
TextBox1.Text = "$" & TextBox1.Text
End If
End If
End Sub
Private Sub TextBox1_Change()
If Len(Mid$(TextBox1.Text, InStr(TextBox1.Text, ".") + 1)) >= 3 Then
TextBox1.Value = Format(PaidCreditCardForfrm.TextBox1.Value, "$#,###")
End If
End Sub