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

0
Andy On

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

Obviously.

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

You can type D into either textbox, no problem.

Markup in mainwindow.

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>
<Window.InputBindings>
    <KeyBinding Key="D"
          Modifiers="Alt" 
          Command="{Binding MyDcommand}" />
</Window.InputBindings>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Ribbon>
        <RibbonGroup>
            <TextBox Text="Hello"/>
        </RibbonGroup>
    </Ribbon>
    <TextBox Height="30" 
             Width="100"
             Grid.Row="1"/>
</Grid>

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
    {
        get
        {
            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