如何:检测 TextBox 中的文本何时更改How to: Detect When Text in a TextBox Has Changed

此示例演示一种在TextChanged TextBox控件中的文本发生更改时使用事件执行方法的一种方法。This example shows one way to use the TextChanged event to execute a method whenever the text in a TextBox control has changed.

XAMLXAML 包含要监视其TextChanged更改的控件的代码隐藏类中,插入每当事件激发时要调用的方法。TextBoxIn the code-behind class for the XAMLXAML that contains the TextBox control that you want to monitor for changes, insert a method to call whenever the TextChanged event fires. 此方法的签名必须与TextChangedEventHandler委托所需的签名相匹配。This method must have a signature that matches what is expected by the TextChangedEventHandler delegate.

只要用户或以编程方式更改TextBox控件的内容,就会调用事件处理程序。The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically.

备注

此事件在创建TextBox控件时和最初用文本填充时引发。This event fires when the TextBox control is created and initially populated with text.

示例Example

在定义控件的中,使用与事件TextChanged处理程序方法名称匹配的值指定特性。 TextBox 可扩展应用程序标记语言 (XAML)Extensible Application Markup Language (XAML)In the 可扩展应用程序标记语言 (XAML)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>

示例Example

XAMLXAML 包含要监视其TextChanged更改的控件的代码隐藏类中,插入每当事件激发时要调用的方法。TextBoxIn the code-behind class for the XAMLXAML that contains the TextBox control that you want to monitor for changes, insert a method to call whenever the TextChanged event fires. 此方法的签名必须与TextChangedEventHandler委托所需的签名相匹配。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.
Private Sub textChangedEventHandler(ByVal sender As Object, ByVal args As TextChangedEventArgs)
    ' Omitted Code: Insert code that does something whenever
    ' the text changes...
End Sub

只要用户或以编程方式更改TextBox控件的内容,就会调用事件处理程序。The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically.

备注

此事件在创建TextBox控件时和最初用文本填充时引发。This event fires when the TextBox control is created and initially populated with text.

注释Comments

请参阅See also