Share via


How to: Handle MouseUp and MouseDown Events for a TextBox

This example shows how to handle MouseUp and MouseDown for a TextBox.

TextBox has built-in handling for the bubbling  MouseUp and events. Consequently, custom event handlers that listen for MouseUp or MouseDown events from a TextBox will never be called. If you need to respond to these events, listen for the tunneling PreviewMouseUp and PreviewMouseDown events instead.

Example

The following Extensible Application Markup Language (XAML) example shows how to use the PreviewMouseUp and PreviewMouseDown attributes to specify the handler delegates for these events.

<TextBox 
  PreviewMouseUp="MouseUpHandler"
  PreviewMouseDown="MouseDownHandler"
/>

The following example shows how to add event listeners programmatically.

TextBox textBox = new TextBox();
textBox.PreviewMouseUp += MouseUpHandler;
textBox.PreviewMouseDown += MouseDownHandler;
// Note: Event listeners can also be added using the AddHandler
// method.

The following example shows empty event handler methods that correspond to the delegates specified in the previous examples.

void MouseUpHandler(Object sender, RoutedEventArgs args)
{
    // This method is called whenever the PreviewMouseUp event fires.
}

void MouseDownHandler(Object sender, RoutedEventArgs args)
{
    // This method is called whenever the PreviewMouseDown event fires.
}

See Also

Concepts

TextBox Overview
RichTextBox Overview