简体   繁体   中英

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

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

eventcallback is invoked in child normally as such

await NewDayScrolledIntoView.InvokeAsync(p1, p2, p3);

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

private void NewDayInView(EmployeeShiftDay dayInView, DateTime weekStart, DateTime weekEnd)
{
   ...
}

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>

You are invoking it deconstructed:

await NewDayScrolledIntoView.InvokeAsync((p1, p2, p3));

When the event is received deconstruct it then:

<ShiftCardScroller NewDayScrolledIntoView="@((args)=> NewDayInView(args.Item1,args.Item2,args.Item3))" />

For me @Brian Parker's solution did not work a slightly modification needed:

(same)

await NewDayScrolledIntoView.InvokeAsync((p1, p2, p3));

Tuple casting:

<ShiftCardScroller NewDayScrolledIntoView="@((args)=> NewDayInView(((EmployeeShiftDay,DateTime,DateTime))args))" />

Method takes one argument. The type is consistent with the previously casted type:

private void NewDayInView((EmployeeShiftDay,DateTime,DateTime)args)
{
   ...
}

you should pass only the name of the Method to the child componant

<ShiftCardScroller NewDayScrolledIntoView="@NewDayInView" ></ShiftCardScroller>

and in the child componant you could invoke the callback with the the parameters that you want

NewDayScrolledIntoView.invokeAsync(Param1,Param1,Param3)

You can use custom Args Type as below:

public class EventCallbackArgs
{
    public bool Confirm { get; set; }
    public Guid Id { get; set; }
    public string Name { get; set; }
}

This is a sample blazor code

<button type="button" class="btn btn-danger" @onclick="() => OnConfirmationChange(true)">
    Delete
</button>

On Delete button click, OnConfirmationChange is called, inside the code of OnConfirmationChange, you can prepare EventCallbackArgs and invoke 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM