【问题标题】:Why is Keyboard.FocusedElement null when focus is inside WindowsFormsHost? It breaks WPF command routing为什么当焦点在 WindowsFormsHost 内时 Keyboard.FocusedElement 为空?它破坏了 WPF 命令路由
【发布时间】:2013-08-28 13:48:08
【问题描述】:

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

<Window.CommandBindings>
    <CommandBinding Command="local:MainWindow.MyCommand" CanExecute="CanExecuteCommmand" Executed="CommandExecuted"/>
</Window.CommandBindings>

这是该命令的唯一处理程序。我还有一个WindowsFormsHost,里面有WinForms的TextBox控件(用于演示目的)。 当焦点在 TextBox 内时,MyCommand 不会到达顶部窗口。当焦点在 WPF 的本机 TextBox 内时,命令处理程序会按预期调用。 p>

我发现 这是因为当焦点位于 WindowsFormsHost 内部时,Keyboard.FocusedElementnull。为什么在这种情况下是 null,它是 WPF 错误还是设计功能?我错过了什么吗?

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

项目源可here

XAML:

<Window x:Class="WpfCommandTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfCommandTest" 
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"  
        Title="MainWindow" Height="480" Width="640" Background="Gray">

    <Window.CommandBindings>
        <CommandBinding Command="local:MainWindow.MyCommand" CanExecute="CanExecuteCommmand" Executed="CommandExecuted"/>
    </Window.CommandBindings>

    <StackPanel Margin="20,20,20,20">
        <TextBox Name="textBoxOutput" Focusable="True" IsTabStop="True" Height="150" Text="WPF TextBox&#x0a;"/>
        <WindowsFormsHost Focusable="True" KeyboardNavigation.IsTabStop="True"  Height="150">
            <wf:TextBox x:Name="textBoxWf" Text="WinForms TextBox" />
        </WindowsFormsHost>
        <Button FocusManager.IsFocusScope="True" Name="btnTest" Focusable="False" IsTabStop="False" Content="Test (ICommand.Execute)" Click="btnTest_Click" Width="200"/>
        <Button FocusManager.IsFocusScope="True" Focusable="False" IsTabStop="False" Content="Test (Command property)" Command="local:MainWindow.MyCommand" Width="200"/>
        <Button FocusManager.IsFocusScope="True" Name="btnClearFocus" Focusable="False" IsTabStop="False" Content="Clear Focus" Click="btnClearFocus_Click" Width="200"/>
    </StackPanel>

</Window>

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));
        }
    }
}

【问题讨论】:

  • 我认为这可能是一个不完美的地方。请参阅此link,部分Focus - Focus works differently for WPF and Windows Forms, and there were some rough edges around here that we were unable to fix。并查看this 文章,可能会有所帮助。
  • 谢谢@AnatoliyNikolaev。我很惊讶他们自 2006 年以来就没有解决这个问题,这让我觉得他们可能永远不会解决这个问题。这部分特别有趣:如果您在 WindowsFormsHost 内有焦点,并且最小化/恢复表单或显示模式对话框,则 WindowsFormsHost 内的焦点可能会丢失 - WindowsFormsHost 仍然具有焦点,但其中的控件可能不是。 我不在乎WindowsFormsHost 中的焦点是什么元素,但​​我希望Keyboard.FocusedElement 指向WindowsFormsHost。你觉得this one怎么样?

标签: c# .net wpf winforms xaml


【解决方案1】:

要完成互操作表单-WPF,您需要这样做:

App.xaml.cs:

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

【讨论】:

  • 不是自动完成的吗?无论如何,谢谢,我会在假期回来时试试这个。
  • 我在问题的示例代码中添加了WindowsFormsHost.EnableWindowsFormsInterop(),但没有任何效果。问题依然存在:当焦点在 WinForms 的TextBox 内部时,MyCommand 没有到达顶部窗口。
猜你喜欢
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
相关资源
最近更新 更多