Windows 8.1 Masked TextBox Behavior

Shortcut to the MaskedTextBoxBehavior on GitHub.

Lack of control

One of my (and several others’) main complaints about the Windows Store App dialect of XAML is the lack of many features/controls that we found in WPF and even Silverlight’s dialect.  Windows 8.1 XAML added some back in (like a Date Picker) but one major lacking control is a Masked Text Box where the user’s input could be guided through a mask (like entering in a phone number).  While WPF lacked one, there were plenty of example out there of people that built them (yaay open source) as well as third party options.  Yet Windows Store Apps had none with the exception of a couple commercial products (DevExpress, for example).  I personally felt there should be one out there in the open source world … so I made one (yaay open source).

Control behaviors

One cool thing I like about XAML controls is the ability to extend the behavior of the control without sub-classing through the use of behaviors.  This allows the developer to use whatever object-oriented hierarchy they want and still pile on different/additional functionality of the control.  This was the approach I choose to take for (my attempt to) add a masked input behavior to Windows Store XAML’s TextBox.

More lack of control

I mistakenly thought this would be a relatively straight-forward task but Windows 8.1 once-again removed some useful functionality like the Preview events, etc. I was left with three events: KeyUp, KeyDown, and TextChanged.  It would have been real nice to use the KeyDown/KeyUp events but I was only provided a “VirtualKey” which was going to make things even more cumbersome so I had no choice but to use TextChanged.  Problem is, TextChanged gives me the text after the user has already entered it.  Time to get creative …

Regular Expressions, Oh My!

Instead of writing my own pattern matching / string parsing logic I decided to rely on Regex processing within the .NET Framework.  However, I didn’t want users of this control to have any needful knowledge of the inner logic so I created a straight-forward expression syntax (like ###-##-####) and generated a regular expression syntax from it.  At this point, it was just a matter of handling most of the fringe cases, copy/paste, etc.

Go and get it! Critique it! Fix it!

In the spirit of righting the wrong I tossed my simple version of this behavior up on GitHub with usage instructions, etc.  It is likely there are better ways of handling things to I welcome any and all contributions and critiques on this!

Leave a comment here if you find it useful!

Advertisements