1

我制作了一个自定义日期选择器控件,以允许输入短日期(例如“010111”、“01012011”或“01-01-2011”)
不知何故,事件不会被触发。

Public Class DatePicker
Inherits System.Windows.Controls.DatePicker

Private Sub DatePicker_PreviewTextInput(sender As Object, e As Windows.Input.TextCompositionEventArgs) Handles Me.PreviewTextInput
    If Me.Text.Length >= 6 Then
        Dim strInput As String = Me.Text.Trim
        Dim dtInput As Date = Nothing

        Select Case strInput.Length
            Case Is = 6
                dtInput = New Date(CInt(Mid(strInput, 5, 2)), CInt(Mid(strInput, 3, 2)), CInt(Mid(strInput, 1, 2)))
            Case Is = 8
                dtInput = New Date(CInt(Mid(strInput, 5, 4)), CInt(Mid(strInput, 3, 2)), CInt(Mid(strInput, 1, 2)))
            Case Is >= 10
                dtInput = New Date(CInt(Mid(strInput, 7, 4)), CInt(Mid(strInput, 4, 2)), CInt(Mid(strInput, 1, 2)))
        End Select

        Me.SelectedDate = dtInput
    End If

    e.Handled = True
End Sub
End Class
4

1 回答 1

0

好的,我以不同的方式解决了它。

Public Class DatePicker
Inherits System.Windows.Controls.DatePicker

Private Sub DatePicker_LostKeyboardFocus(sender As Object, e As Windows.Input.KeyboardFocusChangedEventArgs) Handles Me.LostKeyboardFocus
    Dim dtInput As DateTime
    Dim strInput As String = Me.Text.Trim

    If DateTime.TryParse(strInput, dtInput) = True Then
        Me.SelectedDate = dtInput
    Else
        Select Case strInput.Length
            Case Is = 6
                If DateTime.TryParseExact(Me.Text, "d", New DateTimeFormatInfo() With {.ShortDatePattern = "ddMMyy"}, DateTimeStyles.None, dtInput) Then
                    Me.SelectedDate = dtInput
                End If
            Case Is = 8
                If DateTime.TryParseExact(Me.Text, "d", New DateTimeFormatInfo() With {.ShortDatePattern = "ddMMyyyy"}, DateTimeStyles.None, dtInput) Then
                    Me.SelectedDate = dtInput
                End If
            Case Is >= 10
                If DateTime.TryParseExact(Me.Text, "d", New DateTimeFormatInfo() With {.ShortDatePattern = "dd-MM-yyyy"}, DateTimeStyles.None, dtInput) Then
                    Me.SelectedDate = dtInput
                End If
        End Select
    End If

    e.Handled = True
End Sub End Class
于 2012-10-17T09:22:30.777 回答