【问题标题】:How to get eventdata in Blazor/Razor如何在 Blazor/Razor 中获取事件数据
【发布时间】:2019-10-02 07:57:16
【问题描述】:

我今天开始使用 Blazor,同时已经有一些 web 开发经验。 然而,这似乎还不够。我想获取 onkeydown 事件的 eventarguments,所以我可以检查 enter-key-press。

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

以下是我想从中获取按键的事件。

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

【问题讨论】:

    标签: c# events asp.net-core razor blazor


    【解决方案1】:

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

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

    在 Blazor 中,您将通过以下方式执行此操作:

    <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 在 cmets 中已经提到的,如果您正在编写 onkeypress="@KeyWasPressed",您仍然会得到事件参数

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

    【讨论】:

    • 好的,这似乎可行,谢谢。我现在唯一的问题是我必须按两次 Enter 才能执行我的方法。但是,如果我松开焦点然后再次单击该字段以按 Enter 键,它会第一次起作用。
    • 你也可以写onkeypress="@KeyWasPressed"。你仍然得到 args。
    • 好的,现在解决了。我现在使用 onkeyup。奇迹般有效。再次感谢拉兹万
    • 我使用的是 dotnet 3.1.102,我不得不使用 KeyboardEventArgs 作为事件参数类型而不是 UIKeyboardEventArgs
    猜你喜欢
    • 2021-10-06
    • 2020-10-30
    • 2020-03-31
    • 2022-11-04
    • 2019-12-15
    • 2021-01-21
    • 2020-10-18
    • 2021-11-09
    • 2021-03-21
    相关资源
    最近更新 更多