当焦点在WindowsFormsHost中时,为什么Keyboard.FocusedElement为null? 它打破了WPF命令路由

我有一个自定义的RoutedUICommand MyCommand ,它通过ICommand.Execute执行。 顶部窗口有一个绑定来处理它:

    

这是此命令的唯一处理程序。 我还有一个带有WinForms的TextBox控件的WindowsFormsHost (用于演示目的)。 当焦点位于此TextBoxMyCommand不会到达顶部窗口。 当焦点位于WPF的本机TextBox ,将按预期调用命令处理程序。

我已经发现这种情况正在发生,因为当焦点在WindowsFormsHost时, Keyboard.FocusedElement为null 在这种情况下,为什么它为null ,是WPF错误还是设计function? 我错过了什么吗?

我相信命令应该到达顶部窗口,无论焦点在哪里 (当它是可视树中唯一的处理程序并且FocusManager.IsFocusScope设置正确时)。 我有一个相关的问题 。

项目来源可在此处获得 。

XAML:

          

C#:

 using System; using System.Windows; using System.Windows.Input; namespace WpfCommandTest { public partial class MainWindow : Window { public static readonly RoutedUICommand MyCommand = new RoutedUICommand("MyCommand", "MyCommand", typeof(MainWindow)); const string Null = "null"; public MainWindow() { InitializeComponent(); this.Loaded += (s, e) => textBoxOutput.Focus(); // set focus on the TextBox } void CanExecuteCommmand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } void CommandExecuted(object sender, ExecutedRoutedEventArgs e) { var routedCommand = e.Command as RoutedCommand; var commandName = routedCommand != null ? routedCommand.Name : Null; Log("*** Executed: {0} ***, {1}", commandName, FormatFocus()); } void btnTest_Click(object sender, RoutedEventArgs e) { Log("btnTest_Click, {0}", FormatFocus()); ICommand command = MyCommand; if (command.CanExecute(null)) command.Execute(null); } void btnClearFocus_Click(object sender, RoutedEventArgs e) { FocusManager.SetFocusedElement(this, this); Keyboard.ClearFocus(); Log("btnClearFocus_Click, {0}", FormatFocus()); } void Log(string format, params object[] args) { textBoxOutput.AppendText(String.Format(format, args) + Environment.NewLine); textBoxOutput.CaretIndex = textBoxOutput.Text.Length; textBoxOutput.ScrollToEnd(); } string FormatType(object obj) { return obj != null ? obj.GetType().Name : Null; } string FormatFocus() { return String.Format("focus: {0}, keyboard focus: {1}", FormatType(FocusManager.GetFocusedElement(this)), FormatType(Keyboard.FocusedElement)); } } } 

要完成interop Form-WPF,您需要这样做:

App.xaml.cs:

  public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { WindowsFormsHost.EnableWindowsFormsInterop(); base.OnStartup(e); } }