سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top