Search code examples
c#componentsblazorblazor-server-side

Is there any way to communicate to main layout of blazor pages


Here I want to pass some title to the mainlayout.razor page so that my components or pages can update the title of header. Is there any possible way in blazor to do this ? Any help will be appreciated.

@inherits LayoutComponentBase

<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <div class="main">
        <div class="top-row px-4 bg-success">
            <button onclick="toggleNav()">
                <span class="oi oi-menu"></span>
            </button>
            <div class="text-center">
                hey there
            </div>
        </div>

        <div class="content px-4">
            @Body
        </div>
    </div>
    
</div>

@code
{

}

and my child component is a router page with @page directive to navigate between pages i want that component to update this mainlayout is there any possible way ? Thanks in advance for any help.

Regards,


Solution

  • You should wrap the view portion of the MainLayout component with the CascadingValue component whose value is a reference to the MainLayout itself, so that you can reference the MainLayout component, say, from the Counter component, from which you assign a value string to the property Title defined in the MainLayout component. This property also contain a call to the StateHasChanged method to refresh the display...

     @page "/counter"
    
    
    
    // Gets a reference to the MainLayout component
        [CascadingParameter]
        public MainLayout Layout { get; set; }
    
    
        protected override void OnInitialized()
        {
            Layout.Title = "Greetings from Counter";
    
        }
    

    MainLayout.razor

    @inherits LayoutComponentBase
    
    <CascadingValue Value="this">
        <div class="page">
            <div class="sidebar">
                <NavMenu />
            </div>
    
            <div class="main">
                <div class="top-row px-4">
                    @Title
                    <LoginDisplay />
                    <a href="https://learn.microsoft.com/aspnet/" target="_blank">About</a>
                </div>
    
                <div class="content px-4">
                    @Body
                </div>
            </div>
        </div>
    
    </CascadingValue>
    
    @code
    {
        private string title;
    
        public string Title
        {
            get => title;
            set
            {
                title = value;
                InvokeAsync(() => StateHasChanged());
            }
        }
    }