I have been strugling with passing more than one parameter from child component to parent via EventCaalback.
So here is my working solution:
(.NET 8.02)
Child component:
(ListItem_DC is my object which I want to pass to Parent component togetehr with other bool[] parameter)
<button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, true, false))" >1 Up</button>
<button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, false, false))" >1 Down</button>
<button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, true, true))" >To top</button>
<button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, false, true))" >To bottom</button>
@code {
[Parameter] public ListItem_DC Item { get; set; }
[Parameter] public EventCallback<(ListItem_DC, bool, bool)> OnClickMove {get; set;}
protected virtual async Task OnClickMoveHandler(ListItem_DC item, bool directionUp, bool toTheTopOrBottom)
{
await OnClickMove.InvokeAsync((item, directionUp, toTheTopOrBottom ));
}
}
Parent component
...
<ChildComponent Item="@context" OnClickMove="MoveItemHandler" />
...
@code {
private async Task MoveItemHandler((ListItem_DC item, bool directionUp, bool toTheTopOrBottom) args)
{
//do something with parameters
await MoveItem(args.item, args.directionUp, args.toTheTopOrBottom);
}
}
I tried these topics:
Topic 1
Topic 2
But there is no clear example, so i added it here.
The main reason it is working is the way i’m calling from Parent:
OnClickMove="MoveItemHandler"
and the definition of called fn in Parent:
private async Task MoveItemHandler((ListItem_DC item, bool directionUp, bool toTheTopOrBottom) args)
3
Either:
- define a
readonly struct
to pass the data in a single object, or - use a Tuple.
Here’s a struct:
public readonly record struct ItemData(ListItem_DC Item, bool Up, bool TopToBottom);
Here’s how to use a Tuple.
Note the simplified @onclick
handler.
<button class="my-button" @onclick="() => OnClickMoveHandler(Item, true, false)">1 Up</button>
<button class="my-button" @onclick="() => OnClickMoveHandler(Item, false, false)">1 Down</button>
<button class="my-button" @onclick="() => OnClickMoveHandler(Item, true, true)">To top</button>
<button class="my-button" @onclick="() => OnClickMoveHandler(Item, false, true)">To bottom</button>
@code {
[Parameter] public ListItem_DC? Item { get; set; }
[Parameter] public EventCallback<Tuple<ListItem_DC, bool, bool>> OnClickMove { get; set; }
protected virtual async Task OnClickMoveHandler(ListItem_DC? item, bool directionUp, bool toTheTopOrBottom)
{
await OnClickMove.InvokeAsync(new Tuple<ListItem_DC, bool, bool>(item, directionUp, toTheTopOrBottom));
}
}
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<ChildComponent Item="context" OnClickMove="MoveItemHandler" />
...
@code {
private ListItem_DC context = new();
private async Task MoveItemHandler(Tuple<ListItem_DC, bool, bool> args)
{
//do something with args
await Task.Delay(10);
}
}
1