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

Working with Masked TextBox of Telerik Silverlight RadControls

, 22 Feb 2011
Rate this:
Please Sign up or sign in to vote.
In this article, I am going to describe you all the APIs of Masked TextBox control and the ways to use it to mask your input. Hope this will help you to understand the control in depth.

Editorial Note

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

This is my 3rd day when I explored the Telerik RadControls for Silverlight. Today, I explored the Masked TextBox control of Telerik. It's a good one and gives several options to use.

In this article, I am going to describe you all the APIs of Masked TextBox control and the ways to use it to mask your input. Hope this will help you to understand the control in depth. As always, your feedback and suggestions are always welcome to improve my article content.

Background

Few days ago, I started exploring the Telerik RadControls for Silverlight. I have found many controls and APIs that Telerik controls support on top of the default Silverlight controls.

You can find the previous articles here:
  1.  Day 1: Working with Telerik Silverlight RadControls
  2.  Day 2: Working with BusyIndicator of Telerik Silverlight RadControls
  3.  Day 3: Working with Masked TextBox of Telerik Silverlight RadControls
In this article, we will explore the Masked TextBox control. So, why are you waiting for? Let's start discussing on the same.

Setting up the Project

Hope, you have already installed the Telerik RadControls library for Silverlight. If not, download the trial version from Telerik site. Details are available in the first part of the article series. Once your dev environment is ready, let's start creating our base project.

Open Visual Studio 2010 and open the New Project dialog. Chose Visual C# from the Installed Templates panel at the right side. I am familiar with C# only, hence going with that. From the right panel, chose "RadControls Silverlight Application" as shown in the below screenshot:

image

Give a name for the project and set the working directory in the location. Click Ok to continue. This will open another dialog as shown below:

image

Just click Ok. This will create the web hosting project for your Silverlight application. In general, once you click ok in this screen, it creates the Silverlight project for you. But for Telerik controls project, you have to go thru another screen where you will chose which library assemblies you want to include. Have a look into the below snapshot:

image

For this part of the series, as we want to work with the Masked TextBox control, select the Telerik assembly named "Telerik.Windows.Controls.Input". Once you select this, it will select another shared assembly "Telerik.Windows.Controls" for you as shown below:

image

Click "Finish" to go to the next stage to create the project. The IDE will generate all the pages for you now and open the default "MainPage.xaml" for you in the screen.

More about the Library

Before starting with the other part of the discussion, let us discuss about the library and the Masked TextBox control provided by Telerik. Once the project creation has been done and if you go to the References section of the Silverlight project, you will see that the Telerik.Windows.Controls and the Telerik.Windows.Controls.Input dll reference present in the section.

image

Now inside the Visual Studio IDE, open the Toolbox panel and search for RadMaskedTextBox. You will find the control there as shown in the above figure.

Let's discuss about the control now. Once we became familiar with the control internals, it will be easier for us to develop a sample application with that.

Find herewith the control APIs:

 
namespace Telerik.Windows.Controls
{
    [TemplateVisualState(Name = "Empty", GroupName = "EmptyStates")]
    [TemplateVisualState(Name = "NonEmpty", GroupName = "EmptyStates")]
    public class RadMaskedTextBox : Control
    {
        public static readonly Telerik.Windows.RoutedEvent ValueChangedEvent;
        public static readonly Telerik.Windows.RoutedEvent ValueChangingEvent;
        public static readonly DependencyProperty CultureProperty;
        public static readonly DependencyProperty AutoCompleteIntervalProperty;
        public static readonly DependencyProperty SelectionOnFocusProperty;
        public static readonly DependencyProperty MaskProperty;
        public static readonly DependencyProperty MaskTypeProperty;
        public static readonly DependencyProperty UpdateValueEventProperty;
        public static readonly DependencyProperty PlaceholderProperty;
        public static readonly DependencyProperty IsSpinEnabledProperty;
        public static readonly DependencyProperty ValueProperty;
        public static readonly DependencyProperty EmptyContentTemplateProperty;
        public static readonly DependencyProperty EmptyContentProperty;
        public static readonly DependencyProperty IsEmptyProperty;
        public static readonly DependencyProperty IsFocusedProperty;
        public static readonly DependencyProperty IsReadOnlyProperty;
        public static readonly DependencyProperty TextAlignmentProperty;
        public static readonly DependencyProperty MaskedTextProperty;
        public static readonly DependencyProperty MaxLengthProperty;
        public RadMaskedTextBox();
        public bool IsSpinEnabled { get; set; }
        public CultureInfo Culture { get; set; }
 
        [Obsolete("This property was not used and will be removed.", true)]
        public int AutoCompleteInterval { get; set; }
 
        public bool IsReadOnly { get; set; }
 
        [Obsolete("Please use HorizontalContentAlignment property.", false)]
        public TextAlignment TextAlignment { get; set; }
 
        public string Mask { get; set; }
        public MaskType MaskType { get; set; }
 
        [TypeConverter(typeof (CharConverter))]
        public char Placeholder { get; set; }
 
        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
        public object Value { get; set; }
 
        public string MaskedText { get; set; }
        public int MaxLength { get; set; }
        public SelectionOnFocus SelectionOnFocus { get; set; }
 
        [Category("Behavior")]
        [DefaultValue(false)]
        [Description("Gets the bool indicating whether the control is focused or not. This is a dependency property.")]
        public bool IsFocused { get; internal set; }
 
        public int SelectionLength { get; set; }
        public int SelectionStart { get; set; }
        public object EmptyContent { get; set; }
        public DataTemplate EmptyContentTemplate { get; set; }
        public bool IsEmpty { get; set; }
        public UpdateValueEvent UpdateValueEvent { get; set; }
        public bool CallSpin(bool isUp);
        public override void OnApplyTemplate();
        protected override void OnGotFocus(RoutedEventArgs e);
        protected override void OnLostFocus(RoutedEventArgs e);
        protected override void OnMouseEnter(MouseEventArgs e);
        protected override void OnMouseLeave(MouseEventArgs e);
 
        [Description("Occurs when the value is changed.")]
        [Category("Behavior")]
        public event EventHandler<RadRoutedEventArgs> ValueChanged;
 
        [Category("Behavior")]
        [Description("Occurs before the value is changed.")]
        public event EventHandler<RadMaskedTextBoxValueChangingEventArgs> ValueChanging;
    }
}


You will notice that, it has two states: Empty and NonEmpty. When there are no input text available by the user, it will show the mask inside the textbox. You may chose a different text too. We will try it out later.

It has one property called MaskType, it is enum with three values named None, DateTime, Numeric and Standard.

public enum MaskType { None, DateTime, Numeric, Standard }


Rest of the properties and methods are easily understandable. Hence, we can skip this part and start working on the actual implementation.

Play with the XAML

Let us start playing with the XAML. I assume that, you are familiar with the XAML code. If not, just follow the code mentioned in detail below. If you are familiar with the design view inside VS IDE or Blend, you can chose that too.

Assuming you are familiar with the XAML code, let us add the xmlns namespace for Telerik control. Include the namespace http://schemas.telerik.com/2008/xaml/presentation as shown below in your XAML page:

image

Once added, it will look as below:

image

Well, we are good now to add the control in our page. Let's divide the Grid with one row and two columns and place one RadMaskedTextBox control in one of the cell. It will look as below:

<UserControl x:Class="Day3RadMaskedTextBoxDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
    Width="500" Margin="100">
    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="180"/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Rad Masked TextBox (default):" Grid.Row="0" Grid.Column="0"/>
        <telerik:RadMaskedTextBox Width="200" Height="26" Grid.Row="0" Grid.Column="1"/>
    </Grid>
</UserControl>


The default Masked TextBox control is limited to 4 characters only. If you run the application now, you will be able to see the live version but only 4 characters you can enter. Hence let us divide our default layout Grid with some more rows and columns. Then we will put some more RadMaskedTextBox in our page properly aligned with rows and columns of the Grid control.

Here is my sample code:

<UserControl x:Class="Day3RadMaskedTextBoxDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
    Width="500" Margin="100">
    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="180"/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Masked TextBox (default):" Grid.Row="0" Grid.Column="0"/>
        <telerik:RadMaskedTextBox Width="200" Height="26" Grid.Row="0" Grid.Column="1"/>
 
        <TextBlock Text="Masked TextBox (IP):" Grid.Row="1" Grid.Column="0"/>
        <telerik:RadMaskedTextBox Width="200" Height="26" Grid.Row="1" Grid.Column="1"
                                  Mask="###.###.###.###"/>
        
        <TextBlock Text="Masked TextBox (Date):" Grid.Row="2" Grid.Column="0"/>
        <telerik:RadMaskedTextBox Width="200" Height="26" Grid.Row="2" Grid.Column="1"
                                  Mask="##-##-####"/>
 
        <TextBlock Text="Masked TextBox (Masked Text):" Grid.Row="3" Grid.Column="0"/>
        <telerik:RadMaskedTextBox Width="200" Height="26" Grid.Row="3" Grid.Column="1"
                                  Mask="##/##/####" MaskedText="Enter your DOB"/>
    </Grid>
</UserControl>


You will see that the first control was added is the default control. Now you can set various properties to it. In the 2nd control, we added mask for IP Address. Generally an IP address can contain digits separated with a period (.) and can contain 3 digits in each section. For example, 192.168.028.001 is a valid IP address.

Similarly the 3rd and 4th Masked TextBox control takes Date as input. You can chose how you will show the text by using the mask. You can chose many other properties too as per your requirement.

Demo

Once our coding part is done, let us build and run the sample project. This will clarify everything to you. Once you run the application, you will see the following UI in the browser window. The first textbox is the default one, where you can enter only 4 character. The 2nd will take IP address. The 3rd and 4th TextBox will accept Date in 2 different format.

image

Let me put some text inside each textbox control. Here you can see the behaviour of the Masked TextBox control:

image

Let us do some more customization now. Sometimes, you may want to add a message instead of the underscore (_). Can we do this? Yes, you can set the property called "EmptyContent" and that will handle the thing for you.

Do a sample code for that and here it is:

<TextBlock Text="Masked TextBox (Empty Content):" Grid.Row="4" Grid.Column="0"/>
<telerik:RadMaskedTextBox Width="200" Height="26" Grid.Row="4" Grid.Column="1"
                          Mask="##/##/####" EmptyContent="Enter your DOB"/>


If you run now, you will see the following behaviour:

image

The first textbox shows the default behaviour when the application runs with EmptyContent property set with some text. Once you click on the box, you will see the masked value, as shown in the 2nd Textbox control.

End Note

Hope, you enjoyed reading this article. This will give you the basic idea on how to work with the Telerik Rad Masked TextBox control. I really love this control because, there are no such default control available in Silverlight. You may find it useful in some scenarios in your application and if you know about it earlier, it will be easier for you to integrate.

Keep reading my other articles too and don't forget to share your love by posting a feedback at the bottom. Follow me on twitter at: @kunal2383 and @SilverlightZone for up to date on my tweets. Cheers...

License

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

Share

About the Author

_ Kunal Chowdhury _
Technical Lead
India India
Kunal Chowdhury is a Microsoft "Client Development" MVP (Most Valuable Professional), a Codeproject Mentor, Telerik MVP, Nokia Developer Champion, Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.
 
He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows 8 (WinRT). He posts his findings, articles in his technical blog and CodeProject.
 
Technical Blog: http://www.kunal-chowdhury.com
Facebook: http://facebook.com/blog.kunal
Twitter : http://twitter.com/kunal2383
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionHow to set mode for Password? PinmemberSunasara Imdadhusen31-Jan-12 23:52 
AnswerRe: How to set mode for Password? Pinmvp_ Kunal Chowdhury _1-Feb-12 0:10 
GeneralMy vote of 5 PinmemberAnil_Saran28-Feb-11 18:24 
GeneralRe: My vote of 5 PinmvpKunal_Chowdhury28-Feb-11 18:29 
GeneralMy vote of 5 PinmvpBrij26-Feb-11 7:59 
GeneralRe: My vote of 5 PinmvpKunal_Chowdhury28-Feb-11 18:22 
GeneralI voted 5 and here is why. Pinmembermbcrump24-Feb-11 8:00 
GeneralRe: I voted 5 and here is why. PinmvpKunal_Chowdhury28-Feb-11 18:22 
GeneralMy vote of 2 PinmemberSelvin22-Feb-11 23:54 

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
Web02 | 2.8.140921.1 | Last Updated 22 Feb 2011
Article Copyright 2011 by _ Kunal Chowdhury _
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid