on get double from key down

Brandon Boone 31 Reputation points
2022-06-24T03:47:34.07+00:00

How do I only get a double from a key down ?
so if the user type 4.56
I want to display 4.56
but if they type 4.35 then backspace
I want 4.3
and
not 4.36Back

here is my code:

if (e.Key == Key.Enter || e.Key == Key.Return) return;  
                string letter;  
                if (e.Key == Key.OemPeriod)  
                    letter = ".";  
                else  
                    letter  = e.Key.ToString();  
      
                if (letter.Contains("D"))  
                    letter = Regex.Replace(letter, "D", String.Empty);  
                SliderTxt.Text = SliderTxt.Text + letter;  
  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,278 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
766 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Hui Liu-MSFT 40,266 Reputation points Microsoft Vendor
    2022-06-24T09:10:36.847+00:00

    Or do you want something like the following?
    Xaml:

     <TextBox x:Name="tb2"   Width="200" Height="105"  PreviewTextInput="txt_PreviewTextInput"/>  
    

    Codebehind:

     private void txt_PreviewTextInput(object sender, TextCompositionEventArgs e)  
        {   
    
          foreach (char ch in e.Text)  
            if (!(Char.IsDigit(ch) || ch.Equals('.')))  
            {  
              e.Handled = true;  
            }  
        }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html

    0 comments No comments

  2. Brandon Boone 31 Reputation points
    2022-06-24T16:43:03.99+00:00

    All
    thanks for the help but I got it to work now.

    0 comments No comments