Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

How to find currently focused ListBox

Sometimes I find WPF a bit frustrating - is there a way to find the currently active ListBox in a UserControl from the UserControl itself?

What I want to do is have a property in my UserControl that returns the ListBox that is currently focused within the UserControl.

I've tried this:

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

This doesn't work. Neither does this:

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

Or this:

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

So how do I do this??


Based on Jason Boyd's answer I actually found a solution. And I must say that all this is very little intuitive... -.-

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

Upvotes: 0

Views: 1151

Answers (1)

Jason Boyd
Jason Boyd

Reputation: 7029

What about this:

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

The reason for walking the logical tree is that it is (more than likely) not the listbox itself that has focus but a child object of the listbox.

Upvotes: 1

Related Questions