views:

478

answers:

1

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;
    }
A: 

Both responses (in comments) from Henrik and Johannes contain the best answer for the scenario. Rather than thinking like a Windows Forms programmer and capturing the specific key event, the canonical approach in Silverlight is to use the TextChanged event to remove undesirable characters from a TextBox. A similar question on allowing only numeric input to a TextBox is what prompted the solution that was used.

The following code samples the approach I took after reading the comments and it works quite well to remove characters inappropriate for entry:

    private void fileNameTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        string illegalChars = @"?<>:""\/*|";
        fileNameTextBox.Text = String.Join("", fileNameTextBox.Text.Split(illegalChars.ToCharArray()));
        fileNameTextBox.SelectionStart = fileNameTextBox.Text.Length;
    }
David in Dakota