0

Possible Duplicate:
How do I get a TextBox to only accept numeric input in WPF?

I have a textbox that i only want to accept numeric keys aswell as delete and backspace.

I can allow delete and backspace easily enough, but is there a way to permit all numeric keys as a group (something like Key.Numeric) instead of doing them invidually? Im using wpf so its windows.input.key instead of forms.key.

Community
  • 1
  • 1
richzilla
  • 40,440
  • 14
  • 56
  • 86

2 Answers2

1

If you are searching for masked text box for WPF you can try this library. Here you can find an example of implementation.

Ps Ive found some old sample of such a textBox. You need to hook up to textChanged event. I know its not a perfect solution but might give you basic idea:

int state = 0;
private void IPAddressTxtBox_TextChanged(object sender, TextChangedEventArgs e)
{
            if (state != 1)
            {
                char[] allowedChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };
                string inputText = this.IPAddressTxtBox.Text;

                string result = "";
                foreach (char c in inputText)
                {
                    if (allowedChars.Contains(c))
                    {
                        result += c.ToString();
                    }
                }
                if (!this.IPAddressTxtBox.Text.Equals(result))
                {
                    this.IPAddressTxtBox.Text = result;
                    this.state = 1;
                    this.IPAddressTxtBox.SelectionStart = this.IPAddressTxtBox.Text.Length;
                }

            }
            else if (state == 1)
            {
                state = 2;
            }
        }
mike
  • 550
  • 2
  • 9
  • 24
1

The numerical keys are labelled D0 ... D9 but you prpbaly don't want to rely on this being sequential enum values.

You can create a static lookup:

static HashSet<Key> numKeys = new HashSet<Key> { Key.D0, ... };  

   if (numKeys.Contains(k)) ...
H H
  • 263,252
  • 30
  • 330
  • 514