Add a Masked Textbox control to a WPF program

I found some very creative and technically challenging examples for adding a masked textbox control to a WPF program. Most of them required the creation of a new class inherited from the base System.Windows.Controls.TextBox class. This is a valid option, however, I have implemented a different approach.

I discovered the System.Windows.Forms.Integration.WindowsFormsHost class which is specifically created to support the implementation of Windows Forms controls into a WPF program. Having many years of experience with Windows Forms programs, this was a good find, because there are a number of really good controls written for Windows Forms that can be used in a WPF program via the WindowsFormsHost class. One in particular is a Masked TextBox.

To achieve this add the System.Windows.Forms namespace to the references of you project. Then add the below line of code to the XAML file within the Window element tag.

xmlns:wpfForm= "clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

Open the XAML file you want to add the Masked TextBox to and from the Toolbox tab, drag and drop the WindowsFormsHost onto the WPF window as shown below.

image

Modify the XAML so it resembles the below.

<WindowsFormsHost Height="24" HorizontalAlignment="Left" Margin="23,16,0,0"
                      Name="windowsFormsHost1" VerticalAlignment="Top"
                      Width="70">
       <wpfForm:MaskedTextBox x:Name="maskedTextBoxDate" Mask="00/00/0000" />
</WindowsFormsHost>  

When the program is run, the result is a WPF window with a masked textbox.

image

NOTE: You will need to add the logic to confirm the entered data is in fact a valid date, valid currency value or a valid whatever you choose to mask. This is not done automatically.

It is possible to use generic WPF logic to create and implement a masked textbox, this is just a simpler way of doing it.

Download the source