Home » .NET » VB.NET, WPF & Custom Menu Shortcuts

VB.NET, WPF & Custom Menu Shortcuts

Add the custom command as a reference under the Window definition in the XAML file:

<Window.Resources>
  <RoutedUICommand x:Key="Find_Again" Text="Process" />
</Window.Resources>


Add a key binding to associate a key sequence with the command:

<Window.InputBindings>
  <KeyBinding Key="F3" Command="{StaticResource Find_Again}"/>
</Window.InputBindings>


Add a command binding to configure the action to take when the key binding is used:

<Window.CommandBindings>
  <CommandBinding Command="{StaticResource Find_Again}" Executed="Find_Again_Menu_Item_Click"/>
</Window.CommandBindings>


Finally, configure the menu item to reference the command binding as well:

<MenuItem x:Name="Find_Again_Menu_Item" Header="Find_Again" Command="{StaticResource Find_Again}" InputGestureText="F3"/>


NOTE: When using a command parameter with an object, do not create a handler event or it will get executed twice, once by the command binding and again by the handler.

For example, with the code above, do not construct a sub with a handle like this:

Private Sub Find_Again_Menu_Item_Click(sender As Object, e As RoutedEventArgs) Handles Find_Again_Menu_Item.Click


Instead, just create the sub to handle the action:

Private Sub Find_Again_Menu_Item_Click(sender As Object, e As RoutedEventArgs)

 

References:

ApplicationCommands Class
NavigationCommands Class
MediaCommands Class
EditingCommands Class
ComponentCommands Class

Posted in .NET, Visual Basic, WPF and tagged as ,

Leave a Reply