I am in need of a small utility to do some testing so I decided I would write it in WPF. I'm not that familiar with WPF so I figured this would be a great little application to use to learn.
On my dialog I need an input for "Quantity". I looked for the old faithful NumbericUpDown control but it does not exist. I was sad but decided to push forward.
I placed a textbox down and started figuring out how to block non numeric values. This turned out to be completely different than I expected. Maybe my expectation where wrong. I thought I would start by using the PreviewTextInput event to ensure that the input was a number.
private void TextBoxQuantity_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !e.Text.All(Char.IsNumber);
}
This worked great... except it would not capture the space key (" "). Look as the possible input.

This would not work. I'm not entirely sure why the PreviewTextInput event is not catching the space key but we can fix this by using the PreviewKeyDown event. Let's take a look
private void TextBoxQuantity_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
e.Handled = true;
}
}
Now the textbox will not accept the space input. At this point many would think we are done but we are not. Take a look at what happens if you "Paste" into the textbox.

Well that's no good. We cannot let the user paste text into a NumbericTextBox. We will disable the context menu (copy, cut, paste) and disable the paste command (CTRL + V).
This code will get rid of the context menu.
public MainWindow()
{
InitializeComponent();
TextBoxQuantity.ContextMenu = null;
}
This code will disable the paste command.
XAML
<TextBox CommandManager.PreviewExecuted="TextBoxQuantity_PreviewExecuted" />
Code
private void TextBoxQuantity_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
var commandName = ((RoutedUICommand) (e.Command)).Text;
if (commandName == "Paste")
{
e.Handled = true;
}
}
This is acceptable for my small utility but I will need to figure out how to handle the accepting or rejecting of "pasted" data. It would be nice to still allow the user to paste number into the textbox.
Now we have a textbox that will only accept numeric numbers.