简体   繁体   中英

TextBox LostFocus does not fire

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)
    {

    }

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.

The following behavior will fix this:

public class TextBoxUpdateOnLostKeyboardFocusBehavior : Behavior<TextBox>
{
    protected override void OnAttached()
    {
        if (AssociatedObject != null)
        {
            base.OnAttached();
            AssociatedObject.LostKeyboardFocus += OnKeyboardLostFocus;
        }
    }

    protected override void OnDetaching()
    {
        if (AssociatedObject != null)
        {
            AssociatedObject.LostKeyboardFocus -= OnKeyboardLostFocus;
            base.OnDetaching();
        }
    }

    private void OnKeyboardLostFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        var textBox = sender as TextBox;

        if (textBox != null && e.NewFocus == null)
        {
            // Focus on the closest focusable ancestor
            FrameworkElement parent = (FrameworkElement) textBox.Parent;
            while (parent is IInputElement && !((IInputElement) parent).Focusable)
            {
                parent = (FrameworkElement) parent.Parent;
            }

            DependencyObject scope = FocusManager.GetFocusScope(textBox);
            FocusManager.SetFocusedElement(scope, parent);
        }
    }
}

You can attach it to your TextBox as follows:

 <TextBox>
    <i:Interaction.Behaviors>
        <behaviors1:TextBoxUpdateOnLostKeyboardFocusBehavior />
    </i:Interaction.Behaviors>              
</TextBox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM