Blazor Cascading parameters or a shared service

To implement this in Blazor, we need a shared state that both C2 and Cx can access and modify, enabling changes in one to reflect in the other. This can be done through cascading parameters or a shared service.

Here's how you can implement this scenario:


Solution Using Cascading Parameters

 

@page "/parent"
<h3>Parent Component (P1)</h3>

<CascadingValue Value="SharedState">
    <C1Component />
    <CxComponent />
</CascadingValue>

@code {
    private SharedState SharedState = new SharedState();
}

 

Explanation

  1. Shared State (SharedState):

    • A simple class (SharedState) is created to hold the state of the checkbox (C2Checked).
    • This state is shared among components.
  2. Parent Component (P1):

    • A SharedState instance is created in P1.
    • This instance is passed to child components via CascadingValue.
  3. Child Component 2 (C2Component):

    • C2 updates the SharedState.C2Checked property when its checkbox value changes.
  4. Child Component Cx (CxComponent):

    • Cx binds its checkbox to the same SharedState.C2Checked property.
    • Any changes in C2 are automatically reflected in Cx due to two-way binding.
  5. Cascading Parameters:

    • Both C2Component and CxComponent receive the SharedState object through [CascadingParameter].
    • This ensures the same instance of the state is used by all components.

Up Next
    Ebook Download
    View all
    Learn
    View all
    GE HealthCare will never ask for payment to process documents, refer you to a third party to process