关于C#:如何在Blazor / Razor中获取事件数据

How to get eventdata in Blazor/Razor

我今天开始使用Blazor,同时已经拥有一些Web开发经验。
但是,这似乎还不够。 我想获取onkeydown事件的eventarguments,因此我可以检查是否按下Enter键。

我已经尝试在事件中使用一个函数来检查单独函数中的按键,并且已经尝试将某些内容直接插入onkeydown事件中,但没有任何效果。

以下是我要获取按键的事件。

1
<input onkeydown="" bind="@todo.Title" />

您需要使用UIKeyboardEventArgs,类似于在JavaScript中将事件作为参数传递。

1
<p id="p" onclick="doSomething(event);">

在Blazor中,您可以通过以下方式进行操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<input type="text" onkeypress="@(e => KeyWasPressed(e))" />

/* For .NET Core 3.0+ as per: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.web.keyboardeventargs?view=aspnetcore-3.1 */
@functions {
  private void KeyWasPressed(KeyboardEventArgs args)
  {
    if (args.Key =="r")
    {
      Console.WriteLine("R was pressed");
    }
  }
}

/* For old .NET Core versions */
@functions {
  private void KeyWasPressed(UIKeyboardEventArgs args)
  {
    if (args.Key =="r")
    {
      Console.WriteLine("R was pressed");
    }
  }
}

正如@Bohring在评论中已经提到的那样,如果您正在编写onkeypress="@KeyWasPressed",您仍然会获得事件参数

您可以在此处阅读更多有关其他事件参数的信息:https://visualstudiomagazine.com/articles/2018/10/01/blazor-event-handling.aspx