如何在单独的 .cs 文件中调用 onkeydown 事件

How to call onkeydown event in a separate .cs file

我想在 单独的 C# 代码文件中处理 onkeydown 事件。但是,我总是收到此错误:CS0428 无法将方法组 'KeyHandler' 转换为非委托类型 'object'。您是否打算调用该方法?

恐怕我缺少正确的语法。目标框架是 .NET Standard 2.0。这是我的文件:

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
        }
    }
}

您的代码应该是:

@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
        }
    }
}