FocusLost事件在WPF组件上正常工作。
但对于用户控件,情况有所不同:
如果用户控件中的任何控件被点击或获得焦点,用户控件的FocusLost事件会立即触发!怎么阻止呢?
我无法解决这个问题 :(
FocusLost事件在WPF组件上正常工作。
但对于用户控件,情况有所不同:
如果用户控件中的任何控件被点击或获得焦点,用户控件的FocusLost事件会立即触发!怎么阻止呢?
我无法解决这个问题 :(
UserControl
上的IsKeyboardFocusWithin
属性,以确定UserControl
或其任何子元素是否具有键盘焦点。还有一个事件IsKeyboardFocusWithinChanged
,您可以使用它,只需在事件处理程序中检查e.OldValue
为true
且e.NewValue
为false
即可。
编辑。UserControl
在IsKeyboardFocusWithin
变为false时引发路由事件(UserControlLostFocus
)。<my:UserControl1 UserControlLostFocus="userControl11_UserControlLostFocus"
../>
示例 UserControl
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));
}
}
}
protected override void OnLostFocus(RoutedEventArgs e)
{
e.Handled = true;
}