Create a Simple NumericTextBox Control in Windows Phone 7

Introduction

In this article we are going to explore the controls inside Windows Phone 7 who are named NumericTextBox control. Later we will create a class library, which means we have to take a separate Windows Phone class library for which we can made that numeric TextBox. In this we have to learn how to make a user or custom control from Windows Phone 7. Those are controls in which we can add any type of functionality that we want and later you can use it as a control as well toolbox. Here we are making the numeric TextBox for which means whatever we enter inside the TextBox will be in numeric form, it will not have inserted a character value inside the TextBox. Further, whatever library we have made it's reference such as the .dll file will be added inside the other Windows Phone application at which we want to use that control and you should have to add a library project inside the Windows Phone application project. Now it's time to proceed learning something new so have a look on the steps given below and which will be helpful for such a type of implementation.

Step 1 : In this step we have to create a Windows Phone library so let's see from where you have to add it which is given in the figure.

  • Go to Visual Studio 2010
  • Open New->Project
  • Select the template silverlight for Windows Phone
  • Select the Windows Phone library and give it a name such as WPControls as I give
  • Click OK
Step_1_1fig.jpg

Next-> select the Windows Phone library.

Step_1_2fig.jpg

Step 2 : In this step we will see the code for the Windows Phone library so let's have a look on the code given below.

Code : This code will be written inside the NumericTextBox.cs file

using
System;
using System.Windows.Controls;
using System.Windows.Input;
namespace WPControls
{
  public class NumTxtBox: TextBox
  {
      private readonly Key[] num = new Key[] {Key.Back, Key.NumPad0, Key.NumPad1, Key.NumPad2, Key.NumPad3, Key.NumPad4,
                       Key.NumPad5, Key.NumPad6, Key.NumPad7, Key.NumPad8, Key.NumPad9 };
      public NumTxtBox()
      {
          this.InputScope = new InputScope();
          this.InputScope.Names.Add(new InputScopeName() { NameValue = InputScopeNameValue.TelephoneLocalNumber });
      }
      protected override void OnKeyDown(KeyEventArgs e)
      { 
          if(Array.IndexOf(num,e.Key) == -1)
          {
              e.Handled = true;
          }
          base.OnKeyDown(e);
      }
   }
}

Step 3 : In this step you have to build the class library for which you have to click on the build project; it will be built succesfully as well.

Step 4 : Now you have to take another application which is a Windows Phone application.

  • Start another instance of Visual Studio 2010
  • Go to Menu->File->New->Project
  • Select the Silverlight template for Windows Phone
  • Select the Windows Phone application
  • Click OK

STep_4fig.jpg

Step 5 : In this step you will have to add the reference of the phone class library which was created; let us see from where you have to add this which is shown in the figure.

Step_5_1fig.jpg

Add the reference of the dll file which will be created and see how it will added which is shown in the figure given below.

Step_5_2fig.jpg

Step 6 : In this step we have to add the complete phone library project to the Windows Phone application project; let us see how you will add it.

  • Go to Solution Explorer
  • Right-click and select existing project
  • Select the Class library cs file and add it
  • You will see that the entire library project will be added to the Windows Phone application project

Step_6_1fig.jpg

Add the existing project on click to add it shows which project select existing project.

Step_6_2fig.jpg

Select the WPControls.cs file; let us see how it will added which is shown in the figure.

Step_6_3fig.jpg

Step 7 : In this step you will see that the project has been added to your Windows Phone application project which you can see in the figure given below:

Step_7fig.jpg

Step 8 : In this step you will just see that the control named numeric textbox has been added to the toolbox which you can see in the figure given below you can drag and drop that control to use it.

Step_8_fig.jpg

Step 9 : In this step you just see the code for the MainPage.xaml.cs file which is given below.

Code :

using System;
using System.Windows.Input;
using Microsoft.Phone.Controls;
namespace WPNumericTextBox
{
  public partial class MainPage : PhoneApplicationPage
  {
      // Constructor
      public MainPage()
      {
          InitializeComponent();
      }
      // allowed keys
      private readonly Key[] num = new Key[] {Key.Back, Key.NumPad0, Key.NumPad1, Key.NumPad2, Key.NumPad3, Key.NumPad4,
                       Key.NumPad5, Key.NumPad6, Key.NumPad7, Key.NumPad8, Key.NumPad9 };
      private void STxtbox_KeyDown(object sender, KeyEventArgs e)
      {
          if (Array.IndexOf(num, e.Key) == -1)
          {
              e.Handled = true;
          }
      }
      private void Button2_Click(object sender, System.Windows.RoutedEventArgs e)
      {
          txtbres.Text = string.Format("Numeric textbox 1 value is : {1}{0}Numeric textbox 2 value is : {2}{0}",
          Environment.NewLine,STxtbox.Text,NumTxtboxUC.Text);
      }
      private void Button2_Click(object sender, System.Windows.RoutedEventArgs e)
      {
          txtbres.Text = STxtbox.Text = NumTxtboxUC.Text = string.Empty;
      }
   }
}

Step 10 : In this step you will see the code for the MainPage.xaml file which is given below:

Code:

<
phone:PhoneApplicationPage xmlns:my1="clr-namespace:WPControls;assembly=WPControls"  xmlns:my="clr-namespace:WPNumericTextBox.Controls" 
    x:Class="WPNumericTextBox.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible
="True">
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="My App" Style="{StaticResource PhoneTextNormalStyle}"
                FontFamily
="Comic Sans MS" FontSize="36" Foreground="#FFFFC0FF" />
            <TextBlock x:Name="PageTitle" Text="My Numeric txtbox" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"
                FontSize
="48" FontFamily="Comic Sans MS" Foreground="#FF49FF6F" />
        </StackPanel>
        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="100"/>
                <RowDefinition Height="100"/>
                <RowDefinition Height="100"/>
                <RowDefinition Height="100"/>
                <RowDefinition Height="200"/>
            </Grid.RowDefinitions>
            <StackPanel>
                <TextBlock Foreground="#FF23FFCB" Text="Enter Numeric value" FontFamily="Comic Sans MS" FontSize="26"></TextBlock>
                <TextBox Name="STxtbox" InputScope="TelephoneNumber" KeyDown="STxtbox_KeyDown" FontFamily="Comic Sans MS" FontSize="26" BorderBrush="#BF7B0AFF" />
            </StackPanel>
            <StackPanel Grid.Row="1">
                <TextBlock Foreground="#FF1CA9FF" Text="My Numeric control" FontFamily="Comic Sans MS" FontSize="28"></TextBlock>
                <my:NumericTextBoxUserControl x:Name="NumTxtboxUC" Foreground="#FFFF851B" BorderBrush="#4AC640FF" />
            </StackPanel>
            <StackPanel Grid.Row="4">
                <StackPanel  Orientation="Horizontal" HorizontalAlignment="Center">
                    <Button Name="Button1" Content="Show Data"
                        Click="Button1_Click" FontFamily="Comic Sans MS" FontSize="28" Foreground="#FF30D8C3" />
                    <Button Name="Button2" Content="Clear Data"
                            Click="Button2_Click" FontFamily="Comic Sans MS" FontSize="28" Foreground="#FFF5F300" />
                </StackPanel>
                <TextBlock Name="txtbres"/>
            </StackPanel>
        </Grid>
    </Grid>
</
phone:PhoneApplicationPage>

Step 11 : In this step you will see the design of the MainPage.xaml file let see the figure given below.

Step_10fig.jpg

Step 12 : Now it's time to run the application by pressing F5 let see the output figure which is given below.

Output 1 : Whenever we run the application then by default we will see the figure given below.

Output1.jpg

Output 2 : Now click on the textbox first and second then you can enter only the Numeric value rather than alphabetic.

output2.jpg

Output 3 : In this output after click on the button show values then you can see the values which were written inside both textboxes and you can clear these values on click on the second button named clear values.

Output3.jpg

Here are some other resources which may help you

Next Recommended Readings