InputBindings没有触发以控制菜单可见性



类似于如何在WPF中使用Alt键切换主菜单可见性?我想通过按ALT键来控制菜单的可见性。

我在XAML中有以下内容:

    <Menu Visibility="{Binding IsMenuVisable, Converter={StaticResource BooleanToVisibilityConverter}}">
        <Menu.InputBindings>
            <KeyBinding Key="LeftAlt" Command="{Binding ShowMenuCommand}"/>
            <KeyBinding Key="RightAlt" Command="{Binding ShowMenuCommand}"/>
        </Menu.InputBindings>
        <MenuItem Header="_File">
            <MenuItem Header="Open"/>
        </MenuItem>
    </Menu>

和下面的视图模型:

    private ICommand _ShowMenu;
    public ICommand ShowMenuCommand
    {
        get
        {
            if (_ShowMenu == null)
            {
                _ShowMenu = new RelayCommand(ShowMenu, CanShowMenu);
            }
            return _ShowMenu;
        }
    }
    private void ShowMenu()
    {
        IsMenuVisable = !IsMenuVisable;
    }
    private bool CanShowMenu()
    {
        return true;
    }
    private bool _IsMenuVisable = false;
    public bool IsMenuVisable
    {
        get { return _IsMenuVisable; }
        set
        {
            if (_IsMenuVisable != value)
            {
                _IsMenuVisable = value;
                OnPropertyChanged("IsMenuVisable");
            }
        }
    }

在输出中没有报告关于它无法匹配绑定的错误,但是当我按下alt键时,命令没有执行。我还尝试将InputBindings移动到窗口定义中,认为菜单需要关注InputBindings事件来触发,但我仍然没有让它们触发。

窗口XAML:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Window.DataContext>
    <VM:MainWindowViewModel />
</Window.DataContext>
<Window.InputBindings>
    <KeyBinding Key="LeftAlt" Command="{Binding ShowMenuCommand}"/>
    <KeyBinding Key="RightAlt" Command="{Binding ShowMenuCommand}"/>
</Window.InputBindings>

您需要在绑定中指定 Modifiers 作为 Alt ,因为Alt是为修饰符保留的特殊键之一。

将输入绑定更改为:

<KeyBinding Modifiers="Alt" Key="LeftAlt" Command="{Binding ShowMenuCommand}"/>
<KeyBinding Modifiers="Alt" Key="RightAlt" Command="{Binding ShowMenuCommand}"/>

尝试使用CommandBindings来绑定RouteCommand .

<Window.CommandBindings>
    <CommandBinding Command="{x:Static local:YourView.YourCommand}" Executed="DoSomething"/>
</Window.CommandBindings>

你可以将RouteCommand绑定到Key输入

YourCommand.InputGestures.Add( /*any key combination.*/)

最新更新