Robert Fraser
Robert Fraser

Reputation: 10927

WPF 4 keyboard focus: never recieving key events

In WPF 4.0, I can't seem to get any keyboard shortcuts to work if I swap the user control in the window after it's been loaded. A code sample says a thousand words, so here's what I'm doing:

Window window = new Window { Width = 800, Height = 600 };
window.Loaded += delegate
{
    editor = new EditorRoot();
    window.Content = editor;
};
app.Run(window);

window gets KeyDown events (and routed commands work fine), but editor never gets any keyboard events (nor do any controls within it). I tried:

editor.Loaded += (sender, e) => Keyboard.Focus(editor);

... but that didn't do anything. EditorRoot extends UserControl and has IsFocusable=true Any ideas what's wrong?

Upvotes: 1

Views: 549

Answers (2)

Alex Shtoff
Alex Shtoff

Reputation: 2640

And if this does not work - use Dispatcher.BeginInvoke. From my experience - setting focus synchronously doesn't always work. And not only in WPF 4.

Upvotes: 2

thumbmunkeys
thumbmunkeys

Reputation: 20764

Maybe you could try the FocusManager instead of your approach. I use it and it works, you can even use it in XAML:

         FocusManager.FocusedElement=editor;

Upvotes: 2

Related Questions