简体   繁体   English

为什么命令绑定到按钮的行为与命令绑定菜单项的行为不同?

[英]Why does command binding to a button have different behavior than command binding a menu item?

Consider the following example with a menu and a button: 考虑以下带有菜单和按钮的示例:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
  <DockPanel>
    <Menu DockPanel.Dock="Top">
      <MenuItem Header="Paste" Command="ApplicationCommands.Paste" />
    </Menu>
    <Button Command="ApplicationCommands.Paste">Paste</Button>
    <TextBox>Content</TextBox>
    <TextBox>Content2</TextBox>
  </DockPanel>
</Window>

When I put keyboard focus in one of the text boxes, the TextBox declares that it can handle ApplicationCommands.Paste , and so I expect the button and the menu item to enable themselves. 当我将键盘焦点放在其中一个文本框中时,TextBox声明它可以处理ApplicationCommands.Paste ,因此我希望按钮和菜单项能够启用它们。 What I get instead is that the menu item enables itself, and the button does not. 相反,我得到的是菜单项启用了它本身,而按钮没有启用。 (The button doesn't appear to be "listening" to the TextBox ' CommandBinding ) (该按钮不会出现被“听”到TextBoxCommandBinding

What's going on here, and is there any way I can work around this? 这是怎么回事,有什么办法可以解决这个问题?


EDIT: I did find this question --> WPF routed command enabling works with menu but not with a button <-- but this is not suitable in this case. 编辑:我确实找到了这个问题-> WPF路由命令启用与菜单一起使用,但不适用于按钮 <-,但是在这种情况下不适合。 The button should not be keyboard focusable, and setting it as a focus scope makes it focusable. 该按钮不应是键盘可聚焦的,将其设置为聚焦范围可以使其聚焦。 I can't bind the source, because the actual source needs to be controlled by keyboard focus. 我无法绑定源,因为实际的源需要由键盘焦点控制。

It appears that you can't use the Command property of a button in this manner unless it's contained in a Toolbar. 除非您将其包含在工具栏中,否则您似乎无法以这种方式使用按钮的Command属性。 I get the same results you do with your xaml, but I use the same code regularly to assign this command to a button in a toolbar. 我得到与使用xaml相同的结果,但是我定期使用相同的代码将此命令分配给工具栏中的按钮。

See Copy and paste commands with WPF buttons for more information. 有关更多信息,请参见使用WPF按钮复制和粘贴命令

EDIT: 编辑:

You're right. 你是对的。 It has to do with the FocusScope, and there are two ways to fix it, as shown here: 它与FocusScope有关,有两种解决方法,如下所示:

WPF routed command enabling works with menu but not with a button WPF路由命令启用与菜单一起使用,但不适用于按钮

You can set FocusManager.IsFocusScope on the button: 您可以在按钮上设置FocusManager.IsFocusScope

<Button Command="ApplicationCommands.Paste" FocusManager.IsFocusScope="True">Paste</Button>

Alternately, you can set the button's command target, but this will only work for one textbox. 或者,您可以设置按钮的命令目标,但这仅适用于一个文本框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM