我有一个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)
{
}发布于 2011-11-29 23:42:18
您必须在textbox上使用以下隧道事件: PreviewLostKeyboardFocus
隧道:最初,调用元素树根的事件处理程序。然后,被路由的事件通过沿着路由的连续的子元素向作为被路由的事件源的节点元素(引发被路由的事件的元素)传播。隧道路由的事件通常作为控件合成的一部分使用或处理,使得来自复合部分的事件可以被特定于整个控件的事件故意抑制或替换。WPF中提供的输入事件通常以隧道/冒泡对的形式实现。隧道事件有时也称为预览事件,因为用于对的命名约定。
发布于 2015-10-02 19:05:35
以下行为将解决此问题:
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);
}
}
}您可以将其附加到您的TextBox,如下所示:
<TextBox>
<i:Interaction.Behaviors>
<behaviors1:TextBoxUpdateOnLostKeyboardFocusBehavior />
</i:Interaction.Behaviors>
</TextBox>https://stackoverflow.com/questions/8313192
复制相似问题