I had to communicate between one parent <==> multiple children. The children were created in a foreach loop for a list, so I could not use ref like the answer from "agua from mars".
The answer from "user12228709" seemed usable, but it was too cumbersome to implement with all the interfaces and whatnot. So, I used the same principle but made it simpler by just creating a mediator object and let parent/children communicate through it.
So, create a mediator class that has events, and methods to raise those events, something like
public class Mediator
{
public event EventHandler<string> SomethingChanged;
public void NotifySomethingChanged()
{
Task.Run(() =>
{
SomethingChanged(this, "test");
});
}
}
And then, in the @code of the parent component, create an instance, and passe that to children as a parameter
<ChildComponent MediatorInstance="@MediatorInstance" />
@code
{
Mediator MediatorInstance = new();
Of course, the child receives that as a parameter.
@code
{
[Parameter]
public Mediator MediatorInstance{ get; set; }
Now, bi-directional communication can be done. The side that wants tell others to do something calls a method like NotifySomethingChanged, and the receivers subscribe to relevant events at initialisation.
foreach
loop? – Foxe