C# – TextBox LostFocus does not fire

cwpf

I have a problem with LostFocus event it does not fire when I click on the background.I read some stuff about focus logic and keyboard focus but I could not find a way to get the focus from a control a like textbox when there is only one of them

XAML:

<Grid Height="500" Width="500">
    <TextBox Height="23" Width="120" Margin="12,12,0,0" Name="textBox1" LostFocus="textBox1_LostFocus"  />
</Grid>

C#:

    private void textBox1_LostFocus(object sender, RoutedEventArgs e)
    {

    }

Best Answer

You must use the following tunnelling event : PreviewLostKeyboardFocus on your textbox

Tunneling: Initially, event handlers at the element tree root are invoked. The routed event then travels a route through successive child elements along the route, towards the node element that is the routed event source (the element that raised the routed event). Tunneling routed events are often used or handled as part of the compositing for a control, such that events from composite parts can be deliberately suppressed or replaced by events that are specific to the complete control. Input events provided in WPF often come implemented as a tunneling/bubbling pair. Tunneling events are also sometimes referred to as Preview events, because of a naming convention that is used for the pairs.

Related Topic