Question:
Is there a good way in Silverlight to intercept undesirable characters from being entered into a textbox?
Background:
I have a textbox which allows a user to enter a filename. I would like to exclude invalid file characters from being entered into the textbox. A few of these characters are:
- '?'
- '\'
- '<'
- '>'
Although the Silverlight TextBox class does not support a KeyPress event, it does have a KeyDown and a KeyUp event that can be used to retrieve character information when a key is entered into the textbox. It exposes these as a member of the Key enumeration or it can return an int for the PlatformKeyCode.
Of course the range of keys is larger/different from the range of characters - "F keys" are an example of this. However the presence of something like a KeyPress event in Windows Forms is indicative of the usefulness of being able to extract specific character information.
To do a proof of concept that things could work I hardcoded the PlatformKeyCode values for the undesired characters for my platform into the event handler and everything worked... but of course this is just my platform. I need to make sure this implementation is platform agnostic. Here is the code to demonstrate how I would like it to work:
private void theText_KeyDown(object sender, KeyEventArgs e)
{
int[] illegals = { 191, 188, 190, 220, 186, 222, 191, 56, 186};
if (illegals.Any(i => i == e.PlatformKeyCode)) e.Handled = true;
}