Search code examples
c#wpfkeyeventkeyeventargs

WPF KeyDown method can't be found in class despite being defined


I want the method KeyPress to be called when the enter key is pressed, so I have written the KeyDown event for the whole window into the window definition (shown below):

<Window x:Name="window" x:Class="MoonLander.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MoonLander"
    xmlns:oxy="http://oxyplot.org/wpf"
    mc:Ignorable="d"
    Loaded="OnLoaded"
    KeyDown="KeyPress"
    Title="Moon Lander 2018" Height="580.714" Width="958.824" AutomationProperties.AcceleratorKey="" Background="White">

I have defined the function KeyPress in my MainWindow class like this:

public void KeyPress(object sender, KeyEventArgs e)
{
   //Do something
}

Any ideas why I get this error message? :

Error CS1061 'MainWindow' does not contain a definition for 'KeyPress' and >>no accessible extension method 'KeyPress' accepting a first argument of type >>'MainWindow' could be found (are you missing a using directive or an >>assembly reference?)

Do I need to set the focus to the wi ndow? (I tried to do this using the Loaded="OnLoaded" but have the same error message)

I've tried changing the protection level and changing the first parameter to be a MainWindow object but I get the same error.


Solution

  • My guess is that you coded this by hand, instead of using the IDE to produce the handler. That means the intermediate code does not contain a binding for the event and your method. That binding appears in a hidden file usually named something like this, in your case:

    MainWindow.g.i.cs

    What you should have done is in the XAML, start by typing the event you wish to handle, in this case KeyDown, and then let the IDE do its work by using the TAB key to produce the handler automatically. You should end up with a method like this:

    private void MainWindow_KeyDown(Object sender, KeyEventArgs e)
    {
    }
    

    Note that the auto-generated method is private whereas yours was public. That was the first clue that you did it by hand.