TextBox LostFocus不会触发

TextBox LostFocus不会触发

问题描述:

我遇到LostFocus事件时出现问题,当我点击background.I时,它不会触发。我阅读了一些关于焦点逻辑和键盘焦点的内容,但是我找不到从控件获取焦点的方法如果只有其中一人是像文本框TextBox LostFocus不会触发

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

    } 
+0

那是什么 “背景”:

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); } } } 

如下您可以将它连接到你的文本框? – Tigran

+0

任何东西在这种情况下,在窗口中的网格 – Emre

+1

尝试设置您的文本框的背景颜色,看看它是否完全覆盖网格。如果是这样,顺便点击TextBox。将另一个控件添加到网格并单击它,以便进行有效的测试。 – Tigran

您必须使用下面的隧道连接事件:PreviewLostKeyboardFocus您textbo x

隧道:最初,调用元素树根处的事件处理程序 。然后,路由事件沿着路径传播沿路由的子元素的路由,朝向作为路由事件源(引发路由事件的元素)的节点元素。 隧道路由事件经常被用作或处理为合成控件的一部分,使得来自复合材料部件的事件可以被故意压制或被特定于完全控制的事件替代。在WPF中提供的输入事件通常以实现为隧道/冒泡对的形式实现。隧道事件也是 有时被称为预览事件,因为用于配对的命名约定为 。

+0

嗯,我知道你有多个控件时lostFocus会在控件之间切换时触发我试图找到一种方法来让LostFocus事件触发,当我点击背景时,如果可能的话。 – Emre

+0

@Emre你有没有尝试过让“背景”焦点? – dowhilefor

+0

为什么当你点击背景时,你的文本框必须失去焦点? –

以下行为将解决这个问题:

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