TextBox with only numbers

后端 未结 3 994
谎友^
谎友^ 2021-01-21 04:16

I need to create a TextBox with only numbers but I couldn\'t do. I have tried to put : InputScope = \"Numbers\" but this only work on Mobile. Also I have tried on TextCha

3条回答
  •  不思量自难忘°
    2021-01-21 05:07

    Here is an O(1) solution without string matching

        bool textCanceled = false;
    
        private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (!Char.IsDigit((char)e.Key))
                textCanceled = true;
            else
                textCanceled = false;
    
        }
    
        private void TextBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
        {
            args.Cancel = textCanceled;
        }
    

    might have to handle backspace char as a special case

提交回复
热议问题