Aaaaaaaa
Aaaaaaaa

Reputation: 2114

WPF: UserControl.IsFocused will not set

I created a WPF UserControl, that handles all GotFocus/LostFocus events of its child controls. I call the OnGotFocus/OnLostFocus of the UserControl, but the IsFocused property of the UserControl will not set:

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

How can I set it?

Upvotes: 0

Views: 4017

Answers (3)

user2953609
user2953609

Reputation:

Instead of the IsFocused you can use IsKeyboardFocusWithin

Upvotes: 3

Sheridan
Sheridan

Reputation: 69959

The GotFocus method will be called when the relevant control receives logical focus... from the UIElement.GotFocus Event page on MSDN:

Logical focus differs from keyboard focus if focus is deliberately forced by using a method call but the previous keyboard focus exists in a different scope. In this scenario, keyboard focus remains where it is and the element where a Focus method is called still gets logical focus.

A more precise interpretation of this event is that it is raised when the value of the IsFocused property of an element in the route is changed from false to true.

Because this event uses bubbling routing, the element that receives focus might be a child element instead of the element where the event handler is actually attached. Check the Source in the event data to determine the actual element that gained focus. it will get focus when the user clicks on the relevant control in the UI and/or when you call control.Focus() in your code. The IsFocused is readonly and cannot be set.

Upvotes: 0

Aleksey
Aleksey

Reputation: 1347

use the event UIElement.IsKeyboardFocusWithinChanged and it should worked perfectly.

Upvotes: 3

Related Questions