Reputation: 682
I want to enable only certain keys in UWP TextBox element. But setting e.Handled = false
not helps. All keys accepted.
Similar application in WPF works.
How to solve this problem?
XAML:
<Grid>
<TextBox HorizontalAlignment="Left" Margin="251,166,0,0" VerticalAlignment="Top" KeyDown="TextKeyDown" Height="32" Width="579"/>
</Grid>
C#
private void TextKeyDown(object sender, KeyRoutedEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(e.Key.ToString(), "[0-9]"))
{
e.Handled = false;
System.Diagnostics.Debug.WriteLine("number");
}
else e.Handled = true;
}
Upvotes: 0
Views: 287
Reputation: 21899
Input to the TextBox isn't coming directly through the Key events, and in many cases text input doesn't involves key events at all (think IMEs, auto-complete, on-screen-keyboards, ink input, speech recognition, etc.)
The TextChanging and TextChanged events will fire regardless of the origin of the text and so are better place to implement your filter.
There are pre-built filtering extensions in the Windows Community Toolkit that may suit you rather than rolling your own. Check out TextBoxMask and TextBoxRegex.
Upvotes: 1