im develeoping windows phone 8.1 app. In a textbox I want to prevent the user from inputting any non-digital letter only [0-9].
So here is my code:
Here is a post about a similar topic from the MSDN forums. There appears to be no good way to prevent input, though you could handle it after the fact. The suggested guideline is to allow invalid input but don't do anything with invalid input. For example allow the user to enter a character but don't allow them to submit the form..I don't necessarily agree but if you have to prevent input the CoreWindow.AcceleratorKeyActivated happens 'too soon to tell what character it is.' In your case you're just looking for numbers so I think it should be fine.
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/3c0f5251-9356-4f1d-a148-57024ae71724/testing-for-valid-numeric-and-currency-key-strokes?forum=winappswithcsharp
I ran your code and don't notice the Shift key state switches when the textbox is removed.
I also used the on-screen keyboard and did receive the KeyDown event.
Also, your code did not accept the shifted characters either !@#$%.
In Summary I could not reproduce any of the bugs reported in the post.
Subscribe to the CoreWindow.AcceleratorKeyActivated event. You can check the VirtualKey. This event happens before TextBox.TextChanged so we use this to leverage the routed event framework by filtering which key presses the textbox will handle.
public MainPage()
{
this.InitializeComponent();
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;
}
void Dispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
if (MyTextBox.FocusState != FocusState.Unfocused)
{
if (args.VirtualKey == VirtualKey.Number0 ||
args.VirtualKey == VirtualKey.Number1 ||
args.VirtualKey == VirtualKey.Number2 ||
args.VirtualKey == VirtualKey.Number3 ||
args.VirtualKey == VirtualKey.Number4 ||
args.VirtualKey == VirtualKey.Number5 ||
args.VirtualKey == VirtualKey.Number6 ||
args.VirtualKey == VirtualKey.Number7 ||
args.VirtualKey == VirtualKey.Number8 ||
args.VirtualKey == VirtualKey.Number9)
{
args.Handled = false;
}
else
{
args.Handled = true;
}
}
}