FocusLost事件正在正确处理WPF的组件 对于用户控件,它是不同的:
如果单击或聚焦用户控件中的任何控件,则会立即触发User-Control的FocusLost!我怎么能阻碍它?
我无法解决这个问题:(
答案 0 :(得分:11)
您可以检查IsKeyboardFocusWithin
上的UserControl
,以确定UserControl
或其任何子女是否具有KeyBoard焦点。您还可以使用事件IsKeyboardFocusWithinChanged
,只需在事件处理程序中检查e.OldValue
是否为true
且e.NewValue
为false
。
修改即可。
以下是UserControl
变为false时如何使UserControlLostFocus
引发路由事件(IsKeyboardFocusWithin
)的示例。
可用
<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));
}
}
}
答案 1 :(得分:1)
如果您不想在丢失焦点时触发任何内容,可以将其添加到XAML用户控件后面的源.CS文件中:
protected override void OnLostFocus(RoutedEventArgs e)
{
e.Handled = true;
}