如何找到当前聚焦的ListBox

How to find currently focused ListBox

有时我发现 WPF 有点令人沮丧 - 有没有办法从 UserControl 本身找到 UserControl 中当前活动的 ListBox

我想要做的是在我的 UserControl 中有一个 属性,returns 当前集中在 UserControl 中的 ListBox

我试过这个:

public ListBox FocusedListBox
{
    if (listBox1.IsFocused)
        return listBox1;
    if (listBox2.IsFocused)
        return listBox2;
    return null;
}

这行不通。这也不是:

public ListBox FocusedListBox
{
    if (FocusManager.GetFocusedElement(this) == listBox1)
        return listBox1;
    if (FocusManager.GetFocusedElement(this) == listBox2)
        return listBox2;
    return null;
}

或者这样:

public ListBox FocusedListBox
{
    if (Keyboard.FocusedElement == listBox1)
        return listBox1;
    if (Keyboard.FocusedElement == listBox2)
        return listBox2;
    return null;
}

那么我该怎么做??


根据 Jason Boyd 的回答,我实际上找到了解决方案。而且我必须说,所有这些都非常不直观...... -.-

public ListBox FocusedListBox
{
    get
    {
        var currentObject = Keyboard.FocusedElement as DependencyObject;

        while (currentObject != null && currentObject != this && currentObject != Application.Current.MainWindow)
        {
            if (currentObject == listBox1|| currentObject == listBox2)
            {
                return currentObject as ListBox;
            }
            else
            {
                currentObject = VisualTreeHelper.GetParent(currentObject);
            }
        }

        return null;
    }
}

这个怎么样:

public ListBox FocusedListBox()
{
    DependencyObject currentObject = (UIElement)FocusManager.GetFocusedElement(this);

    while(currentObject != Application.Current.MainWindow)
    {
        if(currentObject == listBox1 || currentObject == listBox2)
        {
            return currentObject as ListBox;
        }
        else
        {
            currentObject = LogicalTreeHelper.GetParent(currentObject);
        }
    }

    return null;
}

遍历逻辑树的原因是(很可能)不是具有焦点的列表框本身而是列表框的子对象。