Blazor EventCallback with Multiple Params - how to respond to event in parent host control

Lau*_*e73 7 webassembly blazor .net-5

I have a blazor component with an EventCallBack parameter that utilized the new struct format allowing multiple arguments

[Parameter] public EventCallback<(EmployeeShiftDay, DateTime, DateTime)> NewDayScrolledIntoView { get; set; }
Run Code Online (Sandbox Code Playgroud)

eventcallback is invoked in child normally as such

await NewDayScrolledIntoView.InvokeAsync(p1, p2, p3);
Run Code Online (Sandbox Code Playgroud)

In my host page I have the corresponding method to handle the invoke

private void NewDayInView(EmployeeShiftDay dayInView, DateTime weekStart, DateTime weekEnd)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

How do I add the markup for this EventCallBack in the host component - I need of course 3 params not just one

<ShiftCardScroller NewDayScrolledIntoView="@((args) => NewDayInView(args))" ></ShiftCardScroller>
Run Code Online (Sandbox Code Playgroud)

Bri*_*ker 10

您正在调用它解构:

await NewDayScrolledIntoView.InvokeAsync((p1, p2, p3));
Run Code Online (Sandbox Code Playgroud)

当接收到事件时,解构它然后:

<ShiftCardScroller NewDayScrolledIntoView="@((args)=> NewDayInView(args.Item1,args.Item2,args.Item3))" />
Run Code Online (Sandbox Code Playgroud)

  • 做了同样的事情,现在我在父组件中收到此错误:CS0119“EventCallback”是一种类型,在给定的上下文中无效 (7认同)

Kha*_*bir 10

您可以使用自定义参数类型,如下所示:

public class EventCallbackArgs
{
    public bool Confirm { get; set; }
    public Guid Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是 blazor 代码示例

<button type="button" class="btn btn-danger" @onclick="() => OnConfirmationChange(true)">
    Delete
</button>
Run Code Online (Sandbox Code Playgroud)

单击“删除”按钮时,将调用OnConfirmationChange,在 OnConfirmationChange 的代码中,您可以准备EventCallbackArgs并调用ConfirmationChanged

[Parameter]
public EventCallback<EventCallbackArgs> ConfirmationChanged { get; set; }
public EventCallbackArgs args { get; set; }

protected async Task OnConfirmationChange(bool deleteCofirmed)
{
    ShowConfirmation = false;
    args = new EventCallbackArgs { Id = id, Name = name };
    args.Confirm = deleteCofirmed;
    await ConfirmationChanged.InvokeAsync(args);
}
Run Code Online (Sandbox Code Playgroud)


Jef*_*ler 8

对我来说@Brian Parker 的解决方案不起作用,需要稍作修改:

(相同的)

await NewDayScrolledIntoView.InvokeAsync((p1, p2, p3));
Run Code Online (Sandbox Code Playgroud)

元组铸造:

<ShiftCardScroller NewDayScrolledIntoView="@((args)=> NewDayInView(((EmployeeShiftDay,DateTime,DateTime))args))" />
Run Code Online (Sandbox Code Playgroud)

方法采用一个参数。类型与之前铸造的类型一致:

private void NewDayInView((EmployeeShiftDay,DateTime,DateTime)args)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

有时需要重新启动 Visual Studio 才能消除不相关的错误消息。