This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Text Input Controls - TextBox

The forty-eighth part of the Windows Presentation Foundation Fundamentals tutorial begins an examination of the WPF controls that allow users to enter text. The first such control is the TextBox, which allows unformatted text input.

Controlling the Input

There are two simple ways in which you can restrict input into a TextBox. The first is to limit the number of characters that are permitted. By default, the MaxLength property is set to zero, indicating that the text is of unlimited length. Changing this integer property to a positive value specifies the maximum number of characters permitted. If the user attempts to enter a longer string, the additional text is not added.

The second restriction that we'll consider here is setting the case of the entered text. This is controlled by the CharacterCasing property, which can be set to a value from the CharacterCasing enumeration. The default option is Normal, meaning that any characters can be entered. You can also elect to use Upper or Lower, limiting the text to upper case or lower case characters respectively. If a letter of the wrong case is typed, it is replaced with one of the correct case.

To demonstrate, modify the XAML for the TextBox as follows:

<TextBox Grid.Row="1"
         Text="Hello, world!"

Now when you run the program you should find that lower case letters are automatically capitalised and that a maximum of fifteen characters can be entered.

Detecting Changes

The last member that we'll consider in this article is the TextChanged event. This event is useful if you need to know immediately when the Text property is changed. When the user is typing, the event is raised once for each added character. When erasing text the event is raised for every press of the backspace or delete keys. If the user selects several characters and presses delete once, the event is raised just once. Similarly, the event is raised once when the user pastes information into a TextBox.

Register the event for the TextBox by modifying the control's XAML for the final time:

<TextBox Grid.Row="1"

Let's make the event update the Label to show the current text whenever it changes:

private void MyTextBox_TextChanged(object sender, TextChangedEventArgs e)
    MyLabel.Content = MyTextBox.Text;

Run the program and type some characters into the TextBox. You should see that the text is immediately duplicated in the lower Label.

4 February 2014