gpt4 book ai didi

c# - FocusLost 在用户控制 [wpf]

转载 作者:太空狗 更新时间:2023-10-29 22:20:18 24 4
gpt4 key购买 nike

FocusLost 事件在 WPF 的组件上正常工作对于用户控件,它是不同的:

如果用户控件中的任何控件被单击或获得焦点,用户控件的 FocusLost 将立即被触发!我怎样才能阻止它?

我无法解决这个问题:(

最佳答案

您可以检查 UserControl 上的 IsKeyboardFocusWithin 以确定 UserControl 或其任何子项是否具有 KeyBoard 焦点。还有事件 IsKeyboardFocusWithinChanged 您可以使用,只需检查 e.OldValue 是否为 truee.NewValue 在事件处理程序中为 false

编辑
下面是一个示例,说明如何在 IsKeyboardFocusWithin 变为 false 时使 UserControl 引发路由事件 (UserControlLostFocus)。

可用如

<my:UserControl1 UserControlLostFocus="userControl11_UserControlLostFocus"
../>

示例用户控件

public partial class UserControl1 : UserControl
{
public static readonly RoutedEvent UserControlLostFocusEvent =
EventManager.RegisterRoutedEvent("UserControlLostFocus",
RoutingStrategy.Bubble,
typeof(RoutedEventHandler),
typeof(UserControl1));
public event RoutedEventHandler UserControlLostFocus
{
add { AddHandler(UserControlLostFocusEvent, value); }
remove { RemoveHandler(UserControlLostFocusEvent, value); }
}

public UserControl1()
{
InitializeComponent();
this.IsKeyboardFocusWithinChanged += UserControl1_IsKeyboardFocusWithinChanged;
}

void UserControl1_IsKeyboardFocusWithinChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if ((bool)e.OldValue == true && (bool)e.NewValue == false)
{
RaiseEvent(new RoutedEventArgs(UserControl1.UserControlLostFocusEvent, this));
}
}
}

关于c# - FocusLost 在用户控制 [wpf],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7111101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com