0

我创建了一个 WPF UserControl,它处理其子控件的所有GotFocus/LostFocus事件。我调用 的OnGotFocus/ OnLostFocusUserControlIsFocused不会设置 UserControl 的属性:

void MyUserControl_Initialized(object sender, EventArgs e)
{
    foreach (UIElement control in (Content as Panel).Children)
    {
        control.LostFocus += control_LostFocus;
        control.GotFocus += control_GotFocus;
    }
}

void control_GotFocus(object sender, RoutedEventArgs e)
{
    if (!IsFocused)
    {
        e.Handled = false;
        OnGotFocus(e);
    }
}

void control_LostFocus(object sender, RoutedEventArgs e)
{
    bool hasAnythingTheFocus = false;

    foreach (UIElement control in (Content as Panel).Children)
    {
        if (control.IsFocused)
        {
            hasAnythingTheFocus = true;
        }
    }

    if (!hasAnythingTheFocus)
    {
        OnLostFocus(e);
    }
}

我该如何设置?

4

3 回答 3

3

使用事件UIElement.IsKeyboardFocusWithinChanged它应该可以完美运行。

于 2013-11-04T11:05:32.967 回答
3

而不是IsFocused你可以使用IsKeyboardFocusWithin

于 2013-11-04T18:49:59.757 回答
0

当相关控件从 MSDN 上的事件页面GotFocus接收到逻辑焦点时,将调用该方法:UIElement.GotFocus

如果焦点是通过使用方法调用故意强制但先前的键盘焦点存在于不同的范围内,则逻辑焦点不同于键盘焦点。在这种情况下,键盘焦点保持在原处,调用 Focus 方法的元素仍然获得逻辑焦点。

对此事件的更准确解释是,当路由中某个元素的 IsFocused 属性的值从 false 更改为 true 时会引发该事件。

由于此事件使用冒泡路由,因此接收焦点的元素可能是子元素,而不是实际附加事件处理程序的元素。检查事件数据中的 Source 以确定获得焦点的实际元素。当用户单击 UI 中的相关控件和/或当您在代码中调用 control.Focus() 时,它将获得焦点。是IsFocusedreadonly不能设置。

于 2013-11-04T11:06:00.623 回答