Capture mouse clicks on WPF TextBox

Robbert Dam picture Robbert Dam · Dec 9, 2009 · Viewed 55.2k times · Source

I want to capture mouse clicks on a TextBox:

<Window x:Class="WpfApplication2.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Grid>
        <TextBox x:Name="t" MouseDown="TextBox_MouseDown"
                 MouseLeftButtonDown="TextBox_MouseLeftButtonDown"
                 MouseLeftButtonUp="TextBox_MouseLeftButtonUp"
                 Height="50" />
    </Grid>
</Window>

Now I only receive a mouse click event when the user first enters the TextBox. After this TextBox has keyboard focus, I do not receive mouse click event anymore. Any idea how to get this working?

Answer

Svetlozar Angelov picture Svetlozar Angelov · Dec 9, 2009

TextBox Class

TextBox has built-in handling for the bubbling MouseUp and MouseDown events. Consequently, custom event handlers that listen for MouseUp or MouseDown events from a TextBox will not be called. If you need to respond to these events, listen for the tunneling PreviewMouseUp and PreviewMouseDown events instead, or register the handlers with the HandledEventsToo argument (this latter option is only available through code). Do not mark the event handled unless you deliberately want to disable TextBox native handling of these events, and be aware that this has notable effects on the control's UI.

In you code you are firing just MouseLeftButtonUp