0

I have problem aboet input number in japanese keyoard which everyone's help.

I have project by C# WPF run on tablet, I want to only allow to input number on my textbox, and I did this on English keyboard. But when I change to japanese keyboard, I can input character and smile symbol.

Please help me only to allow to input number even on japanese keyboard

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Lipton
  • 31
  • 3

3 Answers3

1

Check answer to this question. According to that you need to handle PreviewTextInput event of TextBox like so: <TextBox PreviewTextInput="PreviewTextInput" />. Then inside of it you should set if the text isn't allowed: e.Handled = !IsTextAllowed(e.Text);

private static bool IsTextAllowed(string text)
{
    Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
    return !regex.IsMatch(text);
}

If you want to check user's paste input as well, then you should hook up DataObject.Pasting event as well. So your xaml would look like:

<TextBox PreviewTextInput="PreviewTextInput" 
           DataObject.Pasting="PastingHandler" />

And PastingHandler:

private void PastingHandler(object sender, DataObjectPastingEventArgs e)
{
    if (e.DataObject.GetDataPresent(typeof(String)))
    {
        String text = (String)e.DataObject.GetData(typeof(String));
        if (!IsTextAllowed(text))
        {
            e.CancelCommand();
        }
    }
    else
    {
        e.CancelCommand();
    }
}

Hope this helps.

Community
  • 1
  • 1
Umriyaev
  • 1,150
  • 11
  • 17
0

Are using MVVM if so you should have property bound to your text box, the simplest way to control the allowed values is to check them in the setter

   int text;
    public int Text 
    {
        get
        {
            return text;
        }
        set
        {
            // you can check whatever you want here 

            // for example

            if (value % 2 != 0)
                return;
            text = value;
            RaisePropertyChanged();
        }
    }
Bakri Bitar
  • 1,543
  • 18
  • 29
0

You could try something like this:

xaml:

<TextBox x:Name="NumericTextBox" PreviewTextInput="OnPreviewTextInput"/>

xaml.cs:

private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
}
d.moncada
  • 16,900
  • 5
  • 53
  • 82