如何找到目前专注的ListBox

时间:2015-04-14 18:36:39

标签: c# wpf focus

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

我想要做的是在我的UserControl中添加一个属性,该属性返回当前在ListBox内关注的UserControl

我试过这个:

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;
    }
}

1 个答案:

答案 0 :(得分:1)

这个怎么样:

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;
}

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