Home > Mobile >  Blazor Cascading Parameter always 1 behind
Blazor Cascading Parameter always 1 behind

Time:06-03

I am confused on what I am doing wrong here. In my layout file I have a header section that should change based on which page I am currently on. Here is the layout page.

<CascadingValue Value="this">
<div >
    <NavMenu/>


    <header >
        <div >
            <h1 >@PageTitle</h1>
        </div>
    </header>


    <main>
        <div >
            <div >
                @Body
            </div>
        </div>
    </main>
</div>
</CascadingValue>

<Footer></Footer>

@PageTitle is the variable I am using to control the Header text.

Code Behind declares it as such.

public string PageTitle { get; set; }

Now on my view page I do this in the code behind.

[CascadingParameter]
    public MainLayout? Layout { get; set; }

    protected override void OnInitialized()
    {
        Layout.PageTitle = "Current Page Header";
    }

Problem is it doesn't update properly, it will be blank the first page I go to, then when I click on a different page it will be 1 page behind in the header section. My guess is I am getting something confused with the state right now or I am doing this completely wrong.

Any help is so greatly appreciated.

CodePudding user response:

You'll need to pass the string value to the MainLayout and then call the StateHasChanged method to re-render it.

@code {
        private string _pageTitle ;

        public string PageTitle 
        {
            get => _pageTitle;

            set
            {
                if (_pageTitle != value)
                {
                    _pageTitle = value;
                }

                InvokeAsync(() => StateHasChanged());

            }
        }

    }
  • Related