This is a quick tutorial to show how you can send messages between components in a Blazor WebAssembly (WASM) application. It includes an example Blazor app that sends messages from a home component to a main layout component via a message service.
The tutorial project is available on GitHub at https://github.com/cornflourblue/blazor-webassembly-communication-between-components.
The way to communicate between any two components in a blazor app is to use C# events and delegates, I won’t go too much into the details about how events and delegates work here since it’s a big subject, but in a nutshell they enable publishing and subscribing to events in C#.
A publisher class declares an event
with the type of handler required for the event (a.k.a. the delegate
).
A subscriber class subscribes to an event by adding a handler method (that matches the event delegate) to the event of the publisher class (e.g. publisher.onEvent += myEventHandler;
), and unsubscribes by removing the event handler (e.g. publisher.onEvent -= myEventHandler;
)
For more info on C# events and delegates see https://csharpindepth.com/articles/Events.
#blazor #webassembly #csharp #aspdotnet #developer