Friday, October 29, 2010

Windows Phone 7: Setting numeric keyboard layout for text box

Windows Phone 7 supports different input scopes. Input scope defines the format of input that user is expected to insert. Based on the input scope of current control the on-screen keyboard shows appropriate layout. In this posting I will show you how to use numeric input scope.

Default keyboard layout

Windows Phone 7: Default on-screen keyboard layoutBy default, when you select text box the on-screen keyboard uses qwerty-layout. For text boxes where numbers are expected it is not very convenient for user to switch from qwerty-layout to numeric layout. It is still one additional click that can be avoided.

Setting numeric layout

To get text box use correct keyboard layout we have to modify input scope setting of it. This can be done two different ways: using XAML and using code. In XAML our text box definition will be like this:


<TextBox Height="72" HorizontalAlignment="Left" Margin="12,48,0,0"
Name="numberTextBox" Text="" VerticalAlignment="Top" Width="438">
    <TextBox.InputScope>
        <InputScope NameValue="Number" />
    </TextBox.InputScope
>
</
TextBox
>

If you prefer to set numeric layout in code you can set in page loading event:


void
MainPageLoaded(object sender, RoutedEventArgs e)
{
    var numericScope = new InputScope();
    var numericScopeName = new InputScopeName();
    numericScopeName.NameValue = InputScopeNameValue.Number;
    numericScope.Names.Add(numericScopeName);
    numberTextBox.InputScope = numericScope;           
}

Windows Phone 7: TextBox with Numeric InputScope And here you can see the layout of on-screen keyboard for our numeric text box.

InputScope is about on-screen keyboard layout

InputScope defines only on-screen keyboard layout that is used with text box control. It doesn’t force any validation rules to data that user inserted. It is up to you to validate user input and decide if data is acceptable or not.

If you look at the screenshot on right you can see that user can still switch keyboard to qwerty-layout and if you run application you can try out that inserting letters and other characters to text box is still possible.

You don’t even have to switch to qwerty-layout – even numeric layout has non-numeric symbols you can insert to text box with numeric input scope.

4 comments:

  1. InputScope="Numeric" is wrong, correct is InputScope="Number"

    ReplyDelete
  2. Thanks for feedback! Just fixed the error. :)

    ReplyDelete
  3. Thank you. Very Useful Tip.

    Regards

    KRK

    ReplyDelete
  4. The xaml code not working for me.
    Error:- Error 1 The property 'NameValue' does not exist on the type 'InputScope' in the XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. C:\Users\Rance\Desktop\FusionRetailOnline\FRTouchPos\FRTouchPos\Views\ChildListWindow.xaml 44 21 FRTouchPos

    ReplyDelete