启用启用的 WPF 路由命令适用于菜单,但不适用于按钮



在下面的示例中,当文本接收焦点而不是按钮时,将启用菜单。我只用按钮和文本框尝试过,但行为是一样的。

<Window x:Class="WpfPopup.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  Command="ApplicationCommands.Paste" />
    </Menu>
    <TextBox BorderBrush="Black" BorderThickness="2" Margin="25" TextWrapping="Wrap" x:Name="text1" Height="58" Width="203" >
        The MenuItem will not be enabled until
        this TextBox gets keyboard focus
    </TextBox>        
    <Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" />
</DockPanel>

有两种简单的方法可以解决此问题:

1( 使用 FocusManager.IsFocusScope:

    <Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" FocusManager.IsFocusScope="True"/>

2( 手动设置按钮上的命令目标:

<Button Content="Button" Height="23" Name="button1" Width="93" Command="ApplicationCommands.Paste" CommandTarget="{Binding ElementName=text1}" />

您可能想知道为什么这适用于菜单项?如果您阅读了 FocusManager.IsFocusScope 附加属性的文档,您将获得答案:

默认情况下,Window 类是焦点范围,菜单也是如此, 上下文菜单和工具栏类。作为焦点范围的元素 将 IsFocusScope 设置为 true。

当你不知道的时候,非常困惑!

相关内容

最新更新