Revision as of 02:09, 11 November 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

How to create a PasswordBox with numeric Input Scope on Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article explains how to use a TextBox as PasswordBox with a numeric InputScope.

WP Metro Icon UI.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
SDK: Windows Phone SDK 8.0
Devices(s): Nokia Lumia 820, HTC 8S
Created: vinayppatil (12 Apr 2013)
Updated: Tiziano Cacioppolini (08 Nov 2013)
Last edited: hamishwillee (11 Nov 2013)



A common requirement for password entry is to restrict entry to numeric values only (for example for PIN entry). Unfortunately the PasswordBox does not allow developers to specify a numeric InputScope.

This article shows how to create a password entry text box with numeric InputScope based on a TextBox. This is a simpler approach than creating a custom control.


First add a TextBox to your XAML file, set its InputScope to Number and assign its KeyUp EventHandler to the method we are about to create.

<TextBox Name="PasswordTextBox" InputScope="Number" KeyUp="PasswordTextBox_KeyUp"/>

At this point we have our TextBox with numeric InputScope ready. Now we need to make it look like a PasswordBox by:

  1. Converting user input to a password char before displaying it on the screen.
  2. Handling the cases when press on .(dot) or backspace key. Since only these two keys are non number keys on Numeric key pad.
string _enteredPasscode = "";
string _passwordChar = "*";
private void PasswordTextBox_KeyUp(object sender, KeyEventArgs e)
//modify new passcode according to entered key
_enteredPasscode = GetNewPasscode(_enteredPasscode, e);
ActualPasscode.Text = _enteredPasscode;
//replace text by *
PasswordTextBox.Text = Regex.Replace(_enteredPasscode, @".", _passwordChar);
//take cursor to end of string
PasswordTextBox.SelectionStart = PasswordTextBox.Text.Length;
private string GetNewPasscode(string oldPasscode, KeyEventArgs keyEventArgs)
string newPasscode = string.Empty;
switch (keyEventArgs.Key)
case Key.D0:
case Key.D1:
case Key.D2:
case Key.D3:
case Key.D4:
case Key.D5:
case Key.D6:
case Key.D7:
case Key.D8:
case Key.D9:
newPasscode = oldPasscode + (keyEventArgs.PlatformKeyCode - 48);
case Key.Back:
if (oldPasscode.Length > 0)
newPasscode = oldPasscode.Substring(0, oldPasscode.Length - 1);
newPasscode = oldPasscode;
return newPasscode;

Note.pngNote: _enteredPasscode holds the actual entered passcode in the above example.

Test code

A code example/test code can be downloaded from here: Media:NumericPasswordBoxDemo.zip



This page was last modified on 11 November 2013, at 02:09.
370 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.