tags:

views:

39

answers:

2
<MenuItem x:Name="newProjectButton" Click="OnNewProjectButton_Click" Header="_New Project">
</MenuItem>

I want to call OnNewProjectButton_Click whenever Alt+N is pressed. The code above doesn't work, unfortunately, because the handler is called only if the menu is expanded (i.e. has focus).

+1  A: 

You could use ApplicationCommands.New for this since it already provides that functionality. The default WPF Command Model is pretty cool. Even if you decide not to use the default commanding model, that second link should show you how to hook up the input gestures you need.

EDIT: Here is a sample implementation...

<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.New" 
                    CanExecute="NewApplicationCommand_CanExecute"
                    Executed="NewApplicationCommand_Executed" />
</Window.CommandBindings>

<Grid>

    <Menu>
        <MenuItem Header="_File">
            <MenuItem Command="ApplicationCommands.New" Header="_New Project"  />
        </MenuItem>
    </Menu>

</Grid>

And the code behind...

    private void NewApplicationCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        // Whatever logic you use to determine whether or not your
        // command is enabled.  I'm setting it to true for now so 
        // the command will always be enabled.
        e.CanExecute = true;
    }

    private void NewApplicationCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Console.WriteLine("New command executed");
    }
John L.
A: 

You see to set the InputGestureText on the menu item

<MenuItem Header="Paste" 
 ToolTip="Paste the selected text to text box" 
 InputGestureText="Ctrl+V" />

But unlike WinForms the "The application must handle the user's input to carry out the action".

So consider using the WPF commands as they do this for you automatically. I found that Windows Presentation Foundation Unleashed covers this well.

Ian Ringrose