Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么命令绑定到按钮的行为与命令绑定菜单项的行为不同?_C#_Wpf_Routed Commands - Fatal编程技术网

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

C# 为什么命令绑定到按钮的行为与命令绑定菜单项的行为不同?,c#,wpf,routed-commands,C#,Wpf,Routed Commands,考虑以下带有菜单和按钮的示例: <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="52

考虑以下带有菜单和按钮的示例:

<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>

粘贴
内容
内容2
当我将键盘焦点放在其中一个文本框中时,文本框声明它可以处理
应用程序命令。粘贴
,因此我希望按钮和菜单项能够自行启用。取而代之的是菜单项会自动启用,而按钮不会。(按钮似乎没有“监听”
文本框
命令绑定

这是怎么回事,我有办法解决吗



编辑:我确实发现了这个问题-->似乎不能以这种方式使用按钮的Command属性,除非它包含在工具栏中。我得到了与xaml相同的结果,但我经常使用相同的代码将此命令分配给工具栏中的按钮

有关更多信息,请参阅

编辑:

你说得对。它与聚焦镜有关,有两种方法可以修复它,如下所示:

您可以在按钮上设置
FocusManager.IsFocusScope

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

或者,您可以设置按钮的命令目标,但这仅适用于一个文本框。

如果它在工具栏中工作,则必须有工具栏正在执行的操作来启用此功能,这在其他地方也可以轻松完成。设置IsFocusScope在这种简化情况下有效,但在一般情况下无效。此外,它使按钮可与键盘对焦,这在这里是不受欢迎的。