Search code examples
wpfmvvmfocustabitemonfocus

How to focus a WPF tab item when tab item content is selected?


I have an application whose user interface is made up of a tab control. Each tab item is bound to a view model that has a IsFocused property. It is set correctly when the tab item header gains or loses focus. This works as expected. However, I want the IsFocused property to be set when the tab control's content loses or gains focus.

My use case is that when someone navigates away from the tab item (which causes the IsFocused property on the view model to be set to false) I want the tab item to be reloaded if it has become invalidated once that tab item regains focus. So at the moment if I gain focus on the tab item by clicking on the tab item header and the tab is invalidated then I can reload the tab.

However if I click on the tab content then the IsFocused is not set and hence in the code I cannot determine whether to reload the tab if it has been invalidated. The content for a tab item is a user control containing all my other controls that make up my tab content and I tried binding to the IsFocused property on the user control but this doesn't appear to get set.

I have been on this for days and running out of ideas. Any suggestion would be gratefully received.

Best of regards

Mohammad


Solution

  • Try this code buddy.

            FocusManager.SetFocusedElement(objectToBeFocused);
    

    Focus manager can help you will plenty matters related to WPF focusing.