【问题标题】:Why does command binding to a button have different behavior than command binding a menu item?为什么命令绑定到按钮的行为与命令绑定菜单项的行为不同?
【发布时间】:2013-10-08 05:48:32
【问题描述】:

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

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

当我将键盘焦点放在其中一个文本框中时,TextBox 声明它可以处理ApplicationCommands.Paste,因此我希望按钮和菜单项能够自行启用。相反,我得到的是菜单项自己启用,而按钮没有。 (按钮似乎没有“监听”TextBox'CommandBinding

这是怎么回事,有什么办法可以解决这个问题吗?


编辑:我确实找到了这个问题 --> WPF routed command enabling works with menu but not with a button

【问题讨论】:

    标签: c# wpf routed-commands


    【解决方案1】:

    您似乎不能以这种方式使用按钮的 Command 属性,除非它包含在工具栏中。我得到了与使用 xaml 相同的结果,但我经常使用相同的代码将此命令分配给工具栏中的按钮。

    更多信息请参见Copy and paste commands with WPF buttons

    编辑:

    你是对的。它与 FocusScope 有关,有两种方法可以修复它,如下所示:

    WPF routed command enabling works with menu but not with a button

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

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

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

    【讨论】:

    • 如果它在工具栏中工作,则必须有 ToolBar 正在做的事情来实现这一点,这可以在其他地方轻松完成。
    • 设置 IsFocusScope 在这种简化的情况下有效,但在一般情况下无效。此外,它使按钮可以通过键盘获得焦点,这在此处是不可取的。
    猜你喜欢
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多