Click here to Skip to main content
Click here to Skip to main content
Go to top

WPF Maskable TextBox for Numeric Values

, 19 Mar 2009
Rate this:
Please Sign up or sign in to vote.
Extension of the WPF TextBox which accepts only numeric (integer and floating point) values.

Introduction

This article describes how to enhance the WPF TextBox and make it accept just numeric (integer and floating point) values. The second goal is make the TextBox smart enough to make it easier to input numerics. This is an easy means to provide the TextBox with some kind of intelligence, not just rejecting non-numeric symbols. The provided extension also allows setting minimum and/or maximum values.

If you search in the net, you will probably find some solutions for this problem where developers create their own versions of the TextBox either by inheriting from it or creating a Custom/User Controls that include the standard WPF TextBox. Most other solutions have one major drawback - you would need to replace your TextBox definitions with your new MaskTextBox. Sometimes, it is not painful, sometimes, it is. The reason I chose another solution is that in my case, such kind of changes would be painful.

The approach I’m proposing here is the usage of WPF Attached Properties, which basically are similar to Dependency Properties. The major difference among these to is that Dependency Properties are defined inside the control, but Attached Properties are defined outside. For instance, TextBox.Text is a Dependency Property, but Grid.Column is an Attached Property.

Background (Extending the Functionality of the TextBox)

First of all, I will define an enumeration which tells us whether the TextBox accepts integer, decimal, or any kind of values:

public enum MaskType  
{  
   Any,  
   Integer,  
   Decimal  
}

The next thing would be the definition of the Attached Property.

public class TextBoxMaskBehavior
{
   public static MaskType GetMask(DependencyObject obj)
   {
      return (MaskType)obj.GetValue(MaskProperty);
   }

   public static void SetMask(DependencyObject obj, MaskType value)
   {
      obj.SetValue(MaskProperty, value);
   }

   public static readonly DependencyProperty MaskProperty =
      DependencyProperty.RegisterAttached(
      "Mask",
      typeof(MaskType),
      typeof(TextBoxMaskBehavior),
      new FrameworkPropertyMetadata(MaskChangedCallback)
      );

   private static void MaskChangedCallback(DependencyObject d, 
                       DependencyPropertyChangedEventArgs e)
   {
      // ...
   }
}

Now, we specify the mask for the WPF TextBox like this:

<TextBox local:TextBoxMaskBehavior.Mask="Integer" />

or

<TextBox local:TextBoxMaskBehavior.Mask="Decimal" />

and our assumption would be that the particular TextBox would accept integer and decimal values, respectively. Whenever TestBoxMaskBehavior.Mask is set, MaskChangedCallback is being called. We will add the corresponding handling there.

Background (Subscribing to the TextBox Changes)

The WPF TextBox comes with an event: PreviewTextInput, which allows to listen for text input. It also allows to cancel a particular text input by setting the Handled property of the TextCompositionEventArgs to true. Shown below is an illustrative example:

<TextBox PreviewTextInput="TextBox_PreviewTextInput" />

The C# code:

private static void TextBox_PreviewTextInput(object sender, 
        System.Windows.Input.TextCompositionEventArgs e)
{
   try
   {
      Convert.ToInt32(e.Text);
   }
   catch
   {
      e.Handled = true;
   }
}

Please note that this code is just an example of the PreviewTextInput event usage. My solution has much more useful features rather than checking whether the input text is a number or not Smile | :) .

DataObject.AddPastingHandler(myTextBox, TextBoxPastingEventHandler);
//...
private void TextBoxPastingEventHandler(object sender, DataObjectPastingEventArgs e)
{
   string clipboard = e.DataObject.GetData(typeof(string)) as string;
   try
   {
      Convert.ToInt32(clipboard);
   }
   catch
   {
      e.CancelCommand();
      e.Handled = true;
   }
}

I think that was self-explanatory Smile | :) .

Maskable TextBox

We have covered the techniques that I used in the solution. The full source code and the demo binary are available from the links above. Here is a list of the features available for my Maskable TextBox:

  • Rejects symbols other than digits, negative signs, and the decimal separator.
  • Clamps to minimum/maximum values, if any specified.
  • When typing negative sign, regardless from the caret position, adds it in the beginning if not exist, or removes the existing one.
  • When typing the decimal separator, removes the existing one (if exists), and places the new one in the correct place.
  • And, more useful stuff. Just try to use it. I’m sure you will not regret.

Origin

The origin of this article can be found at WPF Maskable TextBox for Numeric Values.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ruben Hakopian
Software Developer (Senior) Independent Contractor
United States United States

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberviler844-Sep-14 23:25 
QuestionIts not possible to enter the decimal seperator. Pinmemberjens_weller8-Jan-14 23:19 
QuestionDoes not work with binding PinmemberMember 985897917-Jul-13 2:59 
QuestionMaxLength PinmemberMember 1000105720-Apr-13 6:57 
AnswerRe: MaxLength PinmemberMember 1044762028-Jan-14 7:12 
GeneralMy vote of 5 PinmemberKalpesh_Patolia10-Feb-13 20:04 
GeneralMy vote of 5 Pinmemberrjvenugopal27-Jan-13 20:09 
GeneralMy vote of 4 Pinmemberzxzbenjamin24-Dec-12 19:05 
QuestionDelimiter Pinmembermehrdadc488-Apr-12 2:11 
AnswerRe: Delimiter PinmemberRuben Hakopian24-Apr-12 19:22 
GeneralMy vote of 5 PinmemberSan@Coding2-Apr-12 2:16 
Thanx a ton. This is exactly what i was looking for. Very easy to use.
I tried WPF Extended toolkit Mask Edit Control, but that didn't work out for me.
Thanks Ruben...
GeneralMy vote of 5 PinmemberMember 85415585-Jan-12 8:29 
Questionnegative sign rejected [modified] PinmemberRandall Edick25-Aug-11 6:49 
AnswerRe: negative sign rejected [modified] PinmemberRuben Hakopian24-Apr-12 19:25 
GeneralMy vote of 4 Pinmemberwujiong19-Jun-11 22:57 
QuestionGreate work but there is some confusing Pinmemberlaskoteam7-Nov-10 0:05 
QuestionSupport of up/down key? Pinmembermiliu27-Oct-10 7:36 
GeneralVery well done PinmemberMember 378316111-Aug-10 22:08 
GeneralGood Work With Small fall Pinmember=>Joe<=3-Jun-10 2:17 
GeneralGood Work PinmemberFact Pandit3-Feb-10 9:05 
GeneralRe: Good Work PinmemberRuben Hakopian3-Feb-10 9:10 
GeneralRe: Good Work PinmemberFact Pandit6-Sep-10 12:25 
GeneralThank you. Very nice approach. PinmemberRoman Lerman24-Oct-09 20:08 
GeneralGenius PinmemberDotDue20-Oct-09 9:58 
GeneralRe: Genius PinmemberYulian Ustiyanovych23-Nov-09 22:02 
GeneralRe: Genius PinmemberCraig Beuker5-Apr-10 7:21 
GeneralRe: Genius Pinmemberrjvenugopal27-Jan-13 20:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 19 Mar 2009
Article Copyright 2009 by Ruben Hakopian
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid