首页 > 解决方案 > Restrict characters in TextBox of UWP apps

问题描述

My TextBox should only allow what you can type in a basic calculator like numbers 0 to 9 and % * / - + . ( ) So, no letters and other characters. I tried the following from another SO thread but it's not doing anything. You can still type pretty much everything in the TextBox.

private void textBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
   if ((e.Key < VirtualKey.NumberPad0 || e.Key > VirtualKey.NumberPad9) & (e.Key < VirtualKey.Number0 || e.Key > VirtualKey.Number9))
   {
       e.Handled = true;
   }
}

标签: c#uwp

解决方案


private void textBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    if (!Regex.IsMatch(sender.Text, @"^-?\d+\.?\d+[-+*\/]-?\d+\.?\d+$") && sender.Text != "")
    {
        int position = sender.SelectionStart - 1;
        sender.Text = sender.Text.Remove(position, 1);
        sender.SelectionStart = position;
    }
}

推荐阅读