Search code examples
c#.net.net-coreblazorblazor-client-side

How to call onkeydown event in a separate .cs file


I want to handle a onkeydownevent in a separate C# code file. However, I'm always getting this error: CS0428 Cannot convert method group 'KeyHandler' to non-delegate type 'object'. Did you intend to invoke the method?

I'm afraid I'm missing the correct syntax. The target framework is .NET Standard 2.0. Here are my files:

index.razor:

@page "/"
@inherits blazortest.TestBase

<div tabindex="0" @onkeydown=@KeyHandler>
    xxx
</div>

TestBase.cs:

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace blazortest
{
    public class TestBase : LayoutComponentBase
    {
        public void KeyHandler(KeyboardEventArgs e)
        {
            // Do something
        }
    }
}

Solution

  • Your code should be :

    @page "/"
    @inherits blazortest.TestBase
    
    <div tabindex="0" @onkeydown="KeyHandler">
        xxx
    </div>
    
    
    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.Web;
    
    namespace blazortest
    {
        public class TestBase : LayoutComponentBase
        {
            public void KeyHandler(KeyboardEventArgs e)
            {
                // Do something
            }
        }
    }