Pregunta

I'm searching for a way to implement the InputScope of a Textbox like it is done in Wp7, but using classic WPF.

What I want to achieve is, that the input is restricted to only use decimal numbers. How can I achieve that?

<TextBox Text="{Binding Amount, Mode=TwoWay}" InputScope="Number"/>

InputScope is a valid attribute for classic WPF, but sadly it does not seem to work.

¿Fue útil?

Solución

InputScope doesn't force any kind of validation or restriction on the input. It is a hint to input processors (eg. on-screen keyboards, speech recognition) of the kind of data that can be entered in a control.

This value is used only if an IME (like an on-screen keyboard) is activated.

Even in WP7, InputScope doesn't restrict the values that can be entered in a text box. You could still enter unwanted characters if you could install an input processor that ignored InputScope.

If you want to restrict text input to specific characters you will have to use a MaskedTextBox or intercept keystroke events. The code will also be easier to understand.

It may be possible to use InputManager's PreProcessInput event to filter input events using the InputScope but it probably isn't worth the effort.

Otros consejos

There is no built in way to do it. You'll need to write a bit of code to achieve what you're looking for. Here is an example of what you need to do: WPF Maskable TextBox for Numeric Values

I haven't used InputScope, however, from the MSDN documentation (here, here, here and here) it appears that WPF's input scope requires a more complicated input e.g.

xmlns:swi should be mapped to System.Windows.Input.

<TextBox>
    <TextBox.InputScope>
        <swi:InputScope RegularExpression="^(0|(-(((0|[1-9]\d*)\.\d+)|([1-9]\d*))))$" />
    </TextBox.InputScope>
</TextBox>

(Regex string found on Google, I haven't checked it.)


Or perhaps:

<TextBox>
    <TextBox.InputScope>
        <swi:InputScopePhrase>
            <swi:InputScopePhrase.Names>Number</swi:InputScopePhrase>
        </swi:InputScopePhrase>
    </TextBox.InputScope>
</TextBox>
string txt = MessageWrite.Text;
        if (txt != "")
        {
            MessageWrite.Text = Regex.Replace(MessageWrite.Text, "[^a-f ^0-9]", "");
            if (txt != MessageWrite.Text)
            {
                MessageWrite.Select(MessageWrite.Text.Length, 0);
            }
        }

messageWrite is a textbox name. It restricts from A-F and 0-9. User can modify it :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top