Overblog Suivre ce blog
Editer l'article Administration Créer mon blog
16 novembre 2009 1 16 /11 /novembre /2009 15:07

Vous trouverez beaucoup d’exemples de TextBox Numérique pour WPF sur internet. Malheureusement aucun ne prends en compte le remplacement du point par la virgule et n’empêche l’utilisateur de saisir plusieurs virgules. Voici donc un control utilisateur qui prend en compte ces particularités françaises.

 

Code :

Partial Public Class TextBoxNumeric
    Inherits TextBox

    Protected Overloads Overrides Sub OnPreviewTextInput(ByVal e As System.Windows.Input.TextCompositionEventArgs)

        Dim tb As TextBoxNumeric = CType(e.Source, TextBoxNumeric)

        If tb.Text.Contains(".") Or tb.Text.Contains(",") And (e.Text = "." Or e.Text = ",") Then
            e.Handled = True
            Exit Sub
        Else
            If System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator <> "." And e.Text = "." Then
                tb.Text = tb.Text & System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator
                tb.SelectionStart = tb.Text.Length
                e.Handled = True
                Exit Sub
            End If
        End If

        e.Handled = Not AreAllValidNumericChars(e.Text)

        MyBase.OnPreviewTextInput(e)
    End Sub

    Private Function AreAllValidNumericChars(ByVal str As String) As Boolean
        Dim ret As Boolean = True

        If str = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.PerMilleSymbol Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol Or _
            str = System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign Then
            Return ret
        End If

        Dim l As Integer = str.Length
        For i As Integer = 0 To l - 1
            Dim ch As Char = str(i)
            ret = ret And [Char].IsDigit(ch)
        Next

        Return ret
    End Function

End Class

Partager cet article

Repost 0
Published by Cyril - dans WPF
commenter cet article

commentaires