tags:

views:

1517

answers:

3

I've got a WPF browser-like application with a few pages. When I switch between pages, I'd like to set the keyboard focus.

When a page is loaded the first time, this works by calling Control.Focus() in the constructor.

But when I switch between pages this does not work anymore - the focus is just on the first field, and ignores my attempts to change it to anything else :(

The pages have the attribute KeepAlive=true - it would be OK if that would keep the focus alive, too, but just setting the focus to the first field is annoying.

I tried to set the focus in the loaded event, but it did not work, too. It seems the default focus is set after reloading the page.

Is there any way to set the focus on entering a page the second time? When, how and where should I set the focus when switching between WPF pages in a browserlike application?

+1  A: 

Have you tried setting the focus in the Loaded event handler rather than the constructor? Pages aren't re-constructed when you navigate back to them, but they are reloaded if I recall correctly.

Matt Hamilton
Yes, I've tried to set the focus in the Loaded event - does not work, too.
Sam
A: 

Since I found no solution to this problem, I used a simple workaround:

I fire up a secondary thread, which changes the focus after the page has loaded.

Luckily this is done very easily using BeginInvoke:

myControl.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, 
(System.Threading.SendOrPostCallback)delegate(object state) 
{ 
  myControl.Focus(); 
});

This worked way better than I ever expected it to, so probably this workaround will stay in use for a long time.

Sam
+3  A: 

Try Adding FocusManager.FocusedElement="{Binding ElementName=[...]}"`` to the first Element in your Page and set [...] to the name of the element which should get the focus.

Sven Hecht