IntroductionIn this code snippet, explain about create Numeric Textbox in Silverlight. This is pretty simple work, but we have to do some extra work than, when we are create numeric Textbox in C# or Vb.NET. Because in Silverlight, there are does not exist keypress event to the Textbox. So we have to use the keydown for this purpose. ImplementationStep 1As usual create Silverlight project with visual studio 2010 or 2008 Step 2And then add a class calla as NumericTextBox. Then make you are have inherited from existing Textbox object to access exiting members in textbox. Step 3Just compose code like following way, C# Code using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication2
{public class NumericTextBox : TextBox
{protected override void OnKeyDown(KeyEventArgs e)
{if (e.Key < Key.D0 || e.Key > Key.D9)
{if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{if (e.Key != Key.Back && e.Key != Key.Shift)
{
e.Handled = true;
}
}
}
}
}
}
VB.NET code
Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Ink
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Namespace SilverlightApplication2Public Class NumericTextBoxInherits TextBoxProtected Overrides Sub OnKeyDown(e As KeyEventArgs)If e.Key < Key.D0 OrElse e.Key > Key.D9 ThenIf e.Key < Key.NumPad0 OrElse e.Key > Key.NumPad9 ThenIf e.Key <> Key.Back AndAlso e.Key <> Key.Shift Thene.Handled = TrueEnd IfEnd IfEnd IfEnd SubEnd ClassEnd Namespace In above code, I have overridden the keydown event. Within override event, I have checked three conditions to ignore the non number keys. And also allow Back and Shift key as well. Then you can build this project, once you are build you can able to text in toolbox this control as like follows, That's all, then you can drag and drop this in your page, you can use as it usual .NET controls. Sample Project SourceDownload source files -61 kb |