问题
I am trying to allow to register only numbers in TextBox, C# UWP XAML and i dont have the KeyPress Event what should i do?
The WinForms equivalent of what I want to do is this:
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
回答1:
You can use KeyDown
and KeyUp
events. I tested this code on UWP app on Windows 10 OS. Working fine.
<TextBox InputScope="NumberFullWidth" KeyDown="TextBox_KeyDown"></TextBox>
InputScope
will open specific device keyboard on touch device.
private void TextBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
if (e.Key.ToString().Equals("Back"))
{
e.Handled = false;
return;
}
for (int i = 0; i < 10; i++)
{
if (e.Key.ToString() == string.Format("Number{0}", i))
{
e.Handled = false;
return;
}
}
e.Handled = true;
}
PS: You need to change this code to support numbers with decimal points and any other characters (if want to support).
回答2:
If you target Windows 10 Fall Creators Update (introduced v10.0.16299.0) then
you can use the TextBoxBeforeTextChanging
event.
See below example.
private void TextBox_OnBeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
{
args.Cancel = args.NewText.Any(c => !char.IsDigit(c));
}
You can find further explanation and examples here.
回答3:
If you have PreviewTextInput
on UWP you can do it like this also:
<TextBox PreviewTextInput="NumberValidation"/>
private void NumberValidation(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("^[0-9]*$");
e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text));
}
If the Input on the TextBox is a number btw 0 and 9 it will accept the input, if not it will discard it.
If you want to support decimal number or a start with .152
just change the Regex into this:
Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
回答4:
Here is a solution that I use on one of my projects.
class NumericOnlyTextBox : TextBox
{
public NumericOnlyTextBox()
{
this.DefaultStyleKey = typeof(TextBox);
TextChanging += NumericOnlyTextBox_TextChanging;
Paste += NumericOnlyTextBox_Paste;
}
private void NumericOnlyTextBox_Paste(object sender, TextControlPasteEventArgs e)
{
//do not allow pasting (or code it yourself)
e.Handled = true;
return;
}
private void NumericOnlyTextBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
var matchDecimal = Regex.IsMatch(sender.Text, "^\\d*\\.?\\d*$");
var matchInt = Regex.IsMatch(sender.Text, "^\\d*$");
//default - does it match and int?
bool passesTest = matchInt;
//if not matching an int, does it match decimal if decimal is allowed
if (!passesTest && AllowDecimal)
{
passesTest = matchDecimal;
}
//handle the cursor
if (!passesTest && sender.Text != "")
{
int pos = sender.SelectionStart - 1;
sender.Text = sender.Text.Remove(pos, 1);
sender.SelectionStart = pos;
}
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName();
scopeName.NameValue = InputScopeNameValue.NumberFullWidth;
scope.Names.Add(scopeName);
}
public bool AllowDecimal
{
get { return (bool)GetValue(AllowDecimalProperty); }
set { SetValue(AllowDecimalProperty, value); }
}
// Using a DependencyProperty as the backing store for AllowDecimal. This enables animation, styling, binding, etc...
public static readonly DependencyProperty AllowDecimalProperty =
DependencyProperty.Register("AllowDecimal", typeof(bool), typeof(NumericOnlyTextBox), new PropertyMetadata(false));
}
Then you use it like this:
<StackPanel>
<local:NumericOnlyTextBox Width="250" Margin="10" />
<local:NumericOnlyTextBox AllowDecimal="True" Width="250" Margin="10" />
</StackPanel>
Probably not perfect, but it functions well for us and we need to support Anniversary Update, so it should work for you. Regarding other characters, play with the regex and tune it to what you're looking for. Good Luck!
回答5:
Hope, this code helps you.
Use this library,
xmlns:extensions="using:Microsoft.Toolkit.Uwp.UI.Extensions"
and in TextBox control,
extensions:TextBoxRegex.ValidationMode="Dynamic"
extensions:TextBoxRegex.ValidationType="Number"
For example,
<TextBox x:Name="textboxName" Header="Testing" extensions:TextBoxRegex.ValidationMode="Dynamic" extensions:TextBoxRegex.ValidationType="Number" />
Thanks!!!
来源:https://stackoverflow.com/questions/55948742/how-can-i-register-only-numbers-in-textboxi-dont-have-keypress-event