有什么方法可以与 blazor 页面的主布局进行通信

Hum*_*eak 14 c# components blazor blazor-server-side

这里我想将一些标题传递给 mainlayout.razor 页面,以便我的组件或页面可以更新标题的标题。blazor 有没有可能的方法来做到这一点?任何帮助将不胜感激。

@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
{

}
Run Code Online (Sandbox Code Playgroud)

我的子组件是一个带有 @page 指令的路由器页面,用于在页面之间导航我希望该组件更新此主布局,有什么可能的方法吗?预先感谢您的任何帮助。

问候,

Isa*_*aac 20

您应该使用 CascadingValue 组件包装 MainLayout 组件的视图部分,该组件的值是对 MainLayout 本身的引用,以便您可以引用 MainLayout 组件,例如,从 Counter 组件引用 MainLayout 组件,从中您可以将值字符串分配给属性在 MainLayout 组件中定义的标题。此属性还包含对 StateHasChanged 方法的调用以刷新显示...

 @page "/counter"



// Gets a reference to the MainLayout component
    [CascadingParameter]
    public MainLayout Layout { get; set; }


    protected override void OnInitialized()
    {
        Layout.Title = "Greetings from Counter";

    }
Run Code Online (Sandbox Code Playgroud)

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)