views:

230

answers:

1

I've got a WPF window where I have a column of buttons on the left side. On the right side I am show/hiding UserControls as the left hand buttons are clicked.

I have created the UserControls once and then just switch between them with the buttons. As I switch I would like to retain the keyboard focus where it was when that UserControl was last visible.

In other words, I click on button A and show UserControl A. If I move keyboard focus to a textbox in that UserControl then click button B, do some work, then click button A again I would like focus to be on the same textbox that I last used in UserControl A.

Any ideas on how I accomplish this?

+3  A: 

Declare a dictionary with the key being one the left-side buttons and the value the currently focused control. When a button is clicked, get the currently focused element and set it in the dictionary (with the key being the previously clicked button). Change the displayed UserControl and read the dictionary with the key being the just-clicked button. If there is a control for this entry, set the focus to it.

Use FocusManager.FocusedElement to know which control has the focus (actually an IInputElement, which should be the type of the dictionary value) and FocusManager.SetFocusedElement to put the focus back (or call Focus() on the control).

Timores
Awesome. Your advice led me in the right direction. The only additional thing I needed to figure out was that I needed to set FocusManager.IsFocusScope="True" on all of my UserControls and use them as the DependencyObject in the FocusManager calls. Then I followed your logic and additionally had to call Focus() on the UserControl gaining focus as the last step.Thanks Timores!
BrettRobi
You're welcome; sorry about not knowing about IsFocusScope.
Timores