c# - 取决于 UI 焦点状态的 WPF 命令路由行为不一致

标签 c# .net wpf xaml focus

我有一个 RoutedUICommand 命令,可以用两种不同的方式触发:

  • 在按钮点击事件后直接通过 ICommand.Execute
  • 使用声明性语法:<button Command="local:MainWindow.MyCommand" .../>

该命令仅由顶部窗口处理:

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

第一种方法仅在窗口中有焦点元素时才有效。无论焦点如何,第二个总是如此。

我查看了 BCL 的 ICommand.Execute 实现,发现如果 Keyboard.FocusedElementnull 则命令不会被触发,所以这是设计使然。我仍然会质疑,因为顶层可能有一个处理程序(就像我的情况一样)仍然想要接收命令,即使应用程序没有 UI 焦点(例如,我可能想调用 ICommand.Execute从异步任务收到套接字消息时)。就这样吧,我仍然不清楚为什么无论焦点状态如何,第二种(声明性)方法总是有效。

我对 WPF 命令路由的理解遗漏了什么?我确信这“不是错误,而是一项功能”。

下面是代码。如果你喜欢玩它,这里是 full project 。单击第一个按钮 - 命令将被执行,因为焦点在 TextBox 内。单击第二个按钮 - 一切正常。单击 Clear Focus 按钮。现在第一个按钮 ( ICommand.Execute ) 不执行命令,而第二个按钮仍然执行。您需要单击 TextBox 才能使第一个按钮再次起作用,因此有一个焦点元素。

这是一个人为的例子,但它具有现实生活的意义。我将发布一个有关使用 WindowsFormsHost ([EDITED] asked here ) 托管 WinForms 控件的相关问题,在这种情况下,当焦点位于 Keyboard.FocusedElement 内时,null 始终为 WindowsFormsHost(通过 ICommand.Execute 有效地终止命令执行) .

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" 
        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="300"/>

        <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" Margin="138,0,139,0"/>
    </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));
        }
    }
}

[更新] 让我们稍微更改一下代码:

void btnClearFocus_Click(object sender, RoutedEventArgs e)
{
    //FocusManager.SetFocusedElement(this, this);
    FocusManager.SetFocusedElement(this, null);
    Keyboard.ClearFocus();
    CommandManager.InvalidateRequerySuggested();
    Log("btnClearFocus_Click, {0}", FormatFocus());
}

现在我们有另一个有趣的案例:没有逻辑焦点,没有键盘焦点,但是命令仍然被第二个按钮触发,到达顶部窗口的处理程序并被执行(我认为这是正确的行为):

enter image description here

最佳答案

好的,我会尝试按照我的理解来描述这个问题。让我们从 MSDN 的引述开始FAQ 部分(为什么不使用 WPF 命令?):

Additionally, the command handler that the routed event is delivered to is determined by the current focus in the UI. This works fine if the command handler is at the window level, because the window is always in the focus tree of the currently focused element, so it gets called for command messages. However, it does not work for child views who have their own command handlers unless they have the focus at the time. Finally, only one command handler is ever consulted with routed commands.

请注意一行:

who have their own command handlers unless they have the focus at the time.

很明显,当焦点不在的时候,命令是不会执行的。现在的问题是:文档意味着什么?这指的是什么类型的焦点?我提醒有两种类型的焦点:逻辑键盘焦点。

现在引用here :

The element within the Windows focus scope that has logical focus will be used as the command target. Note that it's the windows focus scope not the active focus scope. And it's logical focus not keyboard focus. When it comes to command routing FocusScopes remove any item you place them on and it's child elements from the command routing path. So if you create a focus scope in your app and want a command to route in to it you will have to set the command target manually. Or, you can not use FocusScopes other than for toolbars, menus etc and handle the container focus problem manually.

根据这些来源,可以假设焦点必须处于事件状态,即可以与键盘焦点一起使用的元素,例如:TextBox

为了进一步调查,我对您的示例(XAML 部分)做了一些改动:

<StackPanel Margin="20,20,20,20">
    <StackPanel.CommandBindings>
        <CommandBinding Command="local:MainWindow.MyCommand" CanExecute="CanExecuteCommmand" Executed="CommandExecuted"/>
    </StackPanel.CommandBindings>
    
    <TextBox Name="textBoxOutput" Focusable="True" IsTabStop="True" Height="150" Text="WPF TextBox&#x0a;"/>

    <Menu>
        <MenuItem Header="Sample1" Command="local:MainWindow.MyCommand" />
        <MenuItem Header="Sample2" />
        <MenuItem Header="Sample3" />
    </Menu>

    <Button FocusManager.IsFocusScope="True" 
            Name="btnTest" Focusable="False" 
            IsTabStop="False" 
            Content="Test (ICommand.Execute)" 
            Click="btnTest_Click" Width="200"/>
    
    <Button FocusManager.IsFocusScope="True" 
            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"
            Margin="138,0,139,0"/>
</StackPanel>

我在StackPanel中添加了命令,并添加了Menu控件。现在,如果您单击以清除焦点,则与该命令关联的控件将不可用:

enter image description here

现在,如果我们单击按钮 Test (ICommand.Execute),我们会看到以下内容:

enter image description here

键盘焦点设置在 Window 上,但命令仍未运行。再次记住上面的注释:

Note that it's the windows focus scope not the active focus scope.

他没有主动焦点,所以命令不起作用。它只有在焦点处于事件状态时才有效,设置为 TextBox:

enter image description here

让我们回到原来的例子。

很明显,第一个 Button 没有事件焦点不会导致命令。唯一的区别是,在这种情况下,第二个按钮没有被禁用,因为没有事件焦点,所以点击它,我们直接调用命令。也许,这是由一串 MSDN 引号解释的:

This works fine if the command handler is at the window level, because the window is always in the focus tree of the currently focused element, so it gets called for command messages.

我想,我找到了另一个来源来解释这种奇怪的行为。引自 here :

Menu items or toolbar buttons are by default placed within a separate FocusScope (for the menu or toolbar respectively). If any such items trigger routed commands, and they do not have a command target already set, then WPF always looks for a command target by searching the element that has keyboard focus within the containing window (i.e. the next higher-up focus scope).

So WPF does NOT simply look up the command bindings of the containing window, as you'd intuitively expect, but rather always looks for a keyboard-focused element to set as the current command target! Apparently the WPF team took the quickest route here to make built-in commands such as Copy/Cut/Paste work with windows that contain multiple text boxes or the like; unfortunately they broke every other command along the way.

And here's why: if the focused element within the containing window cannot receive keyboard focus (say, it's a non-interactive image), then ALL menu items and toolbar buttons are disabled -- even if they don't require any command target to execute! The CanExecute handler of such commands is simply ignored.

Apparently the only workaround for problem #2 is to explicitly set the CommandTarget of any such menu items or toolbar buttons to the containing window (or some other control).

关于c# - 取决于 UI 焦点状态的 WPF 命令路由行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417648/

相关文章:

.net - 'dotnet nuget push .. .' doesn' t 似乎在插入符号

c# - 根据属性切换 UserControl

WPF-将静态项目添加到组合框

c# - System.Action<T> 作为 EventHandler

c# - ASP.NET MVC4 不在 IIS 中呈现布局

c# - 如何使用可空的 setter/getter ?

c# - 如何抑制在 C# 中打开 word 文档时显示的 VIsual Basic "Macros are Disabled"对话框

c# - 数据集/内存不足的替换

c# - 使用 BindingOperations.EnableCollectionSynchronization

c# - 使用约束的 Microsoft.SqlServer.Management.Smo.Transfer()