【问题标题】:InputBindings not firing to control menu visibilityInputBindings 未触发以控制菜单可见性
【发布时间】:2014-10-02 10:27:08
【问题描述】:

类似于How can I toggle the main menu visibility using the Alt key in WPF? 我想通过按 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>

欢迎任何想法和建议。

【问题讨论】:

  • 请注意,ALT 键由菜单在内部处理,这就是您的键绑定不会触发的原因。目前我不确定是否以及如何覆盖 ALT 键的菜单内部处理...

标签: c# wpf xaml


【解决方案1】:

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

将输入绑定更改为此:

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

【讨论】:

    【解决方案2】:

    尝试使用 CommandBindings 绑定一个 RouteCommand ..

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

    您可以将 RouteCommand 绑定到按键输入

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 2014-05-26
      • 2012-08-20
      相关资源
      最近更新 更多