Is it possible to implement an TextBox/NumberBox that filters and only accepts numeric values in real time just like what a NumberBox normaly does but not just when the user completes the input and if so how can I do it?
Asked
Active
Viewed 377 times
1 Answers
1
The general approach would be to handle the BeforeTextChanging
event:
private void TextBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewText))
foreach (char c in e.NewText)
if (!char.IsDigit(c))
{
e.Cancel = true;
return;
}
}
XAML:
<TextBox BeforeTextChanging="TextBox_BeforeTextChanging" />

mm8
- 163,881
- 10
- 57
- 88
-
The property BeforeTextChanging doesn't exist. – David Simões Jun 28 '21 at 09:56
-
I's not a property. It's an event and it does exist: https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.textbox.beforetextchanging?WT.mc_id=WD-MVP-5001077 – mm8 Jun 28 '21 at 12:52
-
This works in WinUI3 – Shiva N Nov 14 '22 at 13:44