My key shortcut isn't working

↘锁芯ラ 提交于 2019-12-11 10:21:55

问题


I am tryiong to add a shortcut to my menu Item but It doesn't seams to work.

here is my menu item:

<MenuItem Name="openMenuItem" Header="Open file" InputGestureText="Ctrl+O" Command="{Binding OpenFile}"></MenuItem>

What am I doing wrong here?

here is a picture of my menu:


回答1:


In response to the question you specifically asked:

What am I doing wrong here?

I direct you to the documentation for the InputGestureText property:

This property does not associate the input gesture with the menu item; it simply adds text to the menu item.

It's behaving as designed. InputGestureText just displays some text on the menu item; it does not change behavior, and in particular, it does not actually listen for that key gesture. This is somewhat unexpected, given that the corresponding property in WinForms does add behavior, but it's also called out by the Text suffix on the property name -- it's not the input gesture, it's just the text that's displayed to tell the user about the input gesture. It's set automatically when you use RoutedUICommand, but when you implement ICommand yourself, it's up to you to both set InputGestureText and listen for the key gesture.

What you're doing wrong is expecting this property to behave intuitively. You're far from the only one to be confused by this.

(The obvious follow-on question is "how do I add a keyboard shortcut for my MVVM command", but that's a separate question -- and one that's been asked and answered on StackOverflow multiple times; once you know that's the right question to be asking, you should be able to search for existing answers.)




回答2:


According to Nick at: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/d5536d93-b570-4e21-8668-641fa519cd95/ you need to add code to make it respond to the shortcut, like this:

public Window1()
{
  FilterCommand.InputGestures.Add(new KeyGesture(Key.O, ModifierKeys.Control));
  InitializeComponent();
}



回答3:


There are predefined commands for Open and Close and other common ones. Take a look at : ApplicationCommands

You would have something like :

<Menu DockPanel.Dock="Top">
    <MenuItem Command="ApplicationCommands.Paste" Width="75" />
  </Menu>


来源:https://stackoverflow.com/questions/8227588/my-key-shortcut-isnt-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!