Reputation: 431
It is trivial in Blazor to subscribe a parent control to child's events: in the child, I just declare
[Parameter] Func OnClick { get; set; }
and assign a parent's method to OnClick in the child control markup. However, how can I achieve the opposite? I want the child to react to events from the parent control. So far I am just plain calling child methods from the parent - is there a better approach?
Upvotes: 3
Views: 2849
Reputation: 45764
You can define an event on the parent component which can be handled by subscribers (for instance, a child component) when the event is raised.
Define an event handler, say, StateChanged
public event EventHandler StateChanged;
StateChanged?.Invoke(this, EventArgs.Empty);
// Subscribe to the event defined on the parent component
protected async override Task OnInitAsync()
{
ParentComponent.StateChanged += OnStateChanged;
}
// Dispose of the component
void IDisposable.Dispose()
{
ParentComponent.StateChanged -= OnStateChanged;
}
void OnStateChanged(object sender, EventArgs e) => Call_A_Method_That_Do_Something();
Hope this helps...
Upvotes: 5