Hi guys,
how to get textbox leave event in wpf. I want select next textbox when one textbox leave focus. How to use lostfocus event?

Dani AI

Generated

As found, the simplest way to jump to the next field is to fix the tab order. If you need behavior that runs when a textbox is left (validation, deciding whether to keep focus, or programmatic navigation), use WPF focus events rather than a WinForms-style Leave.

WPF events to consider:

  • Use LostKeyboardFocus / LostFocus for actions that run after focus actually changed.
  • Use PreviewLostKeyboardFocus (the tunneling event) when you need to prevent the control from losing focus (for example, failed validation).

Example: cancel the leave if validation fails (XAML + code-behind)

<TextBox Name="txtField" PreviewLostKeyboardFocus="Txt_PreviewLostKeyboardFocus" />
private void Txt_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    var tb = (TextBox)sender;
    if (string.IsNullOrWhiteSpace(tb.Text))
    {
        // keep focus on this textbox
        e.Handled = true;
    }
}

Example: move focus programmatically (e.g., on Enter or after successful validation)

private void Txt_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        ((UIElement)sender).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        e.Handled = true;
    }
}

Troubleshooting tips: make sure controls are Focusable/IsTabStop and enabled; container TabNavigation settings can change traversal behavior; avoid endless focus loops (if you set focus inside a focus event, consider deferring with Dispatcher.BeginInvoke); for data-binding, UpdateSourceTrigger=LostFocus is useful so validation runs when focus leaves. For more complex validation, integrate WPF validation rules or IDataErrorInfo rather than forcing focus handling in every control.

Hey guys i solved the problem by setting tab order

KeyboardNavigation.TabIndex="2"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.