Click here to Skip to main content
15,886,091 members
Articles / Desktop Programming / WPF

Simple TextBox Derived Custom Control: Filter Key Input

Rate me:
Please Sign up or sign in to vote.
4.29/5 (6 votes)
22 Oct 2010CPOL2 min read 38.9K   1.2K   10   3
This is an example of a Custom Control that inherits from a TextBox and does a simple enhancement to the TextBox

Introduction

I wanted to make some simple controls that would inherit from another control so as to minimize the work required to implement a control and yet have the sophistication of a standard control. I could do it with a control template, but that would limit the flexibility of the final product due to inheritance issues.

One of my problems was that I wanted a textbox that would only let the user enter valid file names; This meant there were some invalid characters that I did not want to allow the user to enter, in this case characters that were invalid for names and directory names. I found some solutions that would help me with creating this textbox on the Internet, but the best I found inherited from a canvas, which seemed a little silly to me since you would not inherit all of the intrinsic capabilities of a TextBox, so I preceded with a control inheriting from a TextBox.

Using the Code

The problem is fairly simple, and only requires that there be a textbox, so you do not have to override many of the intrinsic methods of the TextBox. Really all that is needed is the constructor where an observer method is attached to the PreviewTextInput event. I also added two dependency properties that allow a string containing either invalid or valid characters to be available to the TextBox and a Dependency property that supports INotifyPropertyChanged event that will become true if an invalid character is entered. Having this property allows the user interface to respond to invalid entries.

The XAML that defines the code is very simple since it is really only a TextBox, and the functionality to limit the text input is in the code:

XML
<TextBox x:Class="WPFCustomControls.TextBoxKeyFiltered"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</TextBox>

The most important part of the code is the constructor for the TextBox:

C#
public TextBoxKeyFiltered()
{
    InitializeComponent();
    this.PreviewTextInput += TextBoxKeyFiltered_PreviewTextInput;
    InvalidCharacter = false;
}

The PreviewTextInput is captured because using this event means that you do not need to worry about special keys strokes such as delete, tab and return. The setting of the e.Handled to false in the event handler means that any further processing of the keystroke is aborted. Then all that is needed for the functionality is to create the event handler:

C#
void TextBoxKeyFiltered_PreviewTextInput(object sender, 
	TextCompositionEventArgs e)
{
    if (!string.IsNullOrEmpty(ValidCharacters) && 
        ValidCharacters.IndexOf(e.Text) == -1)
    {
        e.Handled = true;
        InvalidCharacter = true;
        return;
    }
    if (!string.IsNullOrEmpty(InvalidCharacters) && 
        InvalidCharacters.IndexOf(e.Text) > -1)
    {
        e.Handled = true;
        InvalidCharacter = true;
        return;
    }
    e.Handled = false;
    //Reset invalid character
    InvalidCharacter = false;
}

The ValidCharacters and InvalidCharacters are dependency properties that allow the definition of either the only valid text input or only invalid text input in the XAML or using a binding. The InvalidCharacter is a simple property using the PropertyChangedEventHandler to indicate that there has been an invalid input. An event could be defined, but a simple property provides adequate notification to the user application that there has been a bad input, and it can respond to the event in a ViewModel.

The control would be defined within the XAML as:

XML
<control:TextBoxKeyFiltered Grid.Column="1" Grid.Row="1" x:Name="Input"
        Width="200" Margin="2"
        InvalidCharacters="{Binding ElementName=Invalid, Path=Text}"
        ValidCharacters="{Binding ElementName=Valid, Path=Text}"/> 

History

  • 21st October, 2010: Initial version

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAttached Behaviour Pin
Richard Deeming26-Oct-10 8:07
mveRichard Deeming26-Oct-10 8:07 
GeneralMy vote of 5 Pin
Monir Sabbagh25-Oct-10 22:44
Monir Sabbagh25-Oct-10 22:44 
GeneralExcellent Pin
PeterPride25-Oct-10 11:23
PeterPride25-Oct-10 11:23 
example how to create Custom Control. Thanks

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

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