Share via


How to: Detect When Text in a TextBox Has Changed

This example shows one way to use the TextChanged event to execute a method whenever the text in a TextBox control has changed.

In the code-behind class for the XAML that contains the TextBox control that you want to monitor for changes, insert a method to call whenever the TextChanged event fires. This method must have a signature that matches what is expected by the TextChangedEventHandler delegate.

The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically.

Note: This event fires when the TextBox control is created and initially populated with text.

Example

In the Extensible Application Markup Language (XAML) that defines your TextBox control, specify the TextChanged attribute with a value that matches the event handler method name.

<TextBox  TextChanged="textChangedEventHandler">
  Here is the initial text in my TextBox.  Each time the contents of this TextBox are changed, 
  the TextChanged event  fires and textChangedEventHandler is called.
</TextBox>

In the code-behind class for the XAML that contains the TextBox control that you want to monitor for changes, insert a method to call whenever the TextChanged event fires. This method must have a signature that matches what is expected by the TextChangedEventHandler delegate.

// TextChangedEventHandler delegate method.
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{    
    // Omitted Code: Insert code that does something whenever
    // the text changes...
} // end textChangedEventHandler
' TextChangedEventHandler delegate method.
Sub textChangedEventHandler(ByVal sender As Object, ByVal args As TextChangedEventArgs)
    ' Omitted Code: Insert code that does something whenever
    ' the text changes...
End Sub

The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically.

Note: This event fires when the TextBox control is created and initially populated with text.

Comments

See Also

Reference

TextChangedEventArgs

Concepts

TextBox Overview
RichTextBox Overview

Other Resources

Counting Text Changes Sample