用户控制的FocusLost [wpf]

时间:2011-08-18 16:50:15

标签: c# wpf events user-controls focus

FocusLost事件正在正确处理WPF的组件 对于用户控件,它是不同的:

如果单击或聚焦用户控件中的任何控件,则会立即触发User-Control的FocusLost!我怎么能阻碍它?

我无法解决这个问题:(

2 个答案:

答案 0 :(得分:11)

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

修改即可。
以下是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;
}