I have C# WPF application and window with ribbon control and text-box. The ribbon defines many keyboard-shortcuts for the window, e.g. F1, D etc. While the cursor is in the text-box, pressing key D causes calling function associated with that shortcut, so it is impossible to write character "D" in the text-box. Anyone who knows how to solve this problem ?

I tried to override PreviewKeyDown event, also find out which events were fired on pressing key and manipulate them but with no effect.

1 Answers

Andy On

Here's a quick and dirty example intended to give an idea of how shortcut keys are usually implemented.


This is very simplified and my command doesn't do much.

You can type D into either textbox, no problem.

Markup in mainwindow.

    <KeyBinding Key="D"
          Command="{Binding MyDcommand}" />
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
            <TextBox Text="Hello"/>
    <TextBox Height="30" 

I'm using mvvmlight in the viewmodel so it's easy to define icommands.

using GalaSoft.MvvmLight.CommandWpf;
namespace wpf_99
public class MainWindowViewModel : BaseViewModel
    private RelayCommand myDcommand;
    public RelayCommand MyDcommand
            return myDcommand
            ?? (myDcommand = new RelayCommand(
              () =>
                  Console.WriteLine("It worked OK");

When I press Alt+D the command fires whether the textbox is focussed or not.

The command has scope to the window, rather than just the ribbon. So it works if focus is anywhere in the window.

And I can type a D

enter image description here