blazorrazor-components

In Blazor, how to cascade a parameter from @Body back to the layout?


I need to change the class of a spinner in the header - show it while data is being fetched and turn it to invisible when done.

Using Cascading Values, I can have in the layout:

<CascadingValue Value="classString">
    @Body
</CascadingValue>

and in the page I can use [CascadingParameter] string classStr to access the value set in the layout.

If I want classString in the layout affected by a change to classStr in the page, I can cascade an event, as seen here.

But this example cascades the event to a child component with <ChildComponent OnStrChange="@ChangeStr"> where OnStrChange is defined on the child component using [Parameter].

I've tried cascading the event with <CascadingValue Value="eventName" Name="event"> but that does not seem to work.

Can I cascade an event to a page called with @Body?


Solution

  • --edit--

    @enet beat me to the punch on this one, but I'll leave my answer as a slightly more condensed version.

    Layout.razor

    <CascadingValue Value = "this">
        @AnythingThatNeedsAccesToTheSpinner
    </CascadingValue>
    
    @code {
        bool IsSpinning {get; set;}
    
        public async Task SetSpinner (bool SpinValue){
            IsSpinning=SpinValue;
        }
    }
    

    AnythingThatNeedsAccessToTheSpinner.razor

    @code{
        [CascadingParameter]
        Layout Layout {get; set;}
    
        protected override async Task OnInitializedAsync()
        {
             await Layout.SetSpinner(true);
             await Task.Delay(5000);
             await Layout.SetSpinner(false);
        }
        
    }