Go Back

Masking input in wpf

I found a great blog about masking input with wpf here

http://karlhulme.wordpress.com/2007/02/15/masking-input-to-a-wpf-textbox/#comment-452

 

Basically, i was using this code to create textboxes that inherit from System.Windows.Controls.TextBox for Ssn, Phone, and zipcode.

To start out with , i just want to limit user input to numbers, so i have created a simple static method to handle that (based off Karl's work)

    internal class NumericOnlyMask

    {

        internal static bool IsTextAllowed(string text)

        {

            return Array.TrueForAll<char>(text.ToCharArray(),

                delegate(char c) { return char.IsDigit(c); });

        }

    }

Then my PhoneTextBox is pretty simple, it only cares about having 10characters and using the above numeric only mask.

    public class PhoneTextBox : System.Windows.Controls.TextBox

    {

        protected override void OnTextInput(System.Windows.Input.TextCompositionEventArgs e)

        {

            e.Handled = !(Srg.Applications.TempApply.Converters.NumericOnlyMask.IsTextAllowed(e.Text)

                && (this.Text.Length + e.Text.Length - this.SelectedText.Length) <= 10);

 

            base.OnTextInput(e);

        }

 

    }

Putting the control onto my xaml page was pretty simple, first i had to add the clr-namespace

 

<Page

      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

      xmlns:d="http://schemas.microsoft.com/expression/blend/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"

  xmlns:controls="clr-namespace:Srg.Applications.TempApply.Controls"

      >

Then just use it:

 

        <controls:PhoneTextBox Height="Auto" Text="{Binding HomePhone}" TextWrapping="Wrap" x:Name="txtPhoneNumber" HorizontalAlignment="Left" Margin="8,145.851,0,0" ToolTip="Your primary phone number in which you prefer to be contacted" VerticalAlignment="Top" Width="159.9" Grid.Column="2" Grid.Row="1">

        </controls:PhoneTextBox>

 

Facebook DZone It! Digg It! StumbleUpon Technorati Del.icio.us NewsVine Reddit Blinklist Furl it!

Post a comment!
  1. Formatting options