As your Blazor application grows, components will need to collaborate. Communication between them can be done in several ways, and Blazor provides us with simple and efficient tools for this purpose:
✅ 1. EventCallback – bottom-up communication
Used to send events from a child component to its parent.
👇 Example: Button in a child component that adds an item
AddItemForm.razor:
<input @bind="ItemName" placeholder="Item name" />
<button @onclick="Send">Add</button>
@code {
private string ItemName;
[Parameter]
public EventCallback<string> OnItemAdded { get; set; }
private async Task Send()
{
if (!string.IsNullOrWhiteSpace(ItemName))
{
await OnItemAdded.InvokeAsync(ItemName);
ItemName = "";
}
}
}
ParentComponent.razor:
<AddItemForm OnItemAdded="AddItem" />
<ul>
@foreach (var item in Items)
{
<li>@item</li>
}
</ul>
@code {
private List<string> Items = new();
private void AddItem(string newItem)
{
Items.Add(newItem);
}
}
✅ 2. [CascadingParameter] – top-down communication for global values
Ideal for providing common data (e.g., theme, culture, authentication, etc.) to multiple components.
App.razor:
<CascadingValue Value="GlobalMessage">
<MainLayout />
</CascadingValue>
@code {
private string GlobalMessage = "Hello from the global context!";
}
Any child component can receive this value:
@code {
[CascadingParameter]
public string GlobalMessage { get; set; }
}
🧠 Conclusion
Communication between components is essential in any modern application. EventCallback allows you to react to events, while CascadingParameter facilitates sharing global values without a rigid structure. Next week we will discuss Forms and Validation in Blazor.