Search code examples
wpftextboxfocusitemscontrol

Getting UI Element that has keyboardFocus from itemscontrol


I have a itemscontrol that displays some textboxes dependning on the observable collection items in viewmodel. I need to determine the textbox that has keyboard focus on click of a button outside the itemscontrol.

Problem: 1. When i click the button the keyboard focus shifts to button instead of the textbox. 2. How can i get the a ui element that has keyboard focus inside the itemscontrol.

Thanks in advance for suggestions.


Solution

  • You'll need to use logical focus and a focus scope inside the ItemsControl:

    <ItemsControl x:Name="_itemsControl" FocusManager.IsFocusScope="true"/>
    

    Then, in your code behind:

    var focusedElement = FocusManager.GetFocusedElement(_itemsControl);