如何在 App.razor 中设置后更改 blazor 中的默认布局?

How to change the default layout in blazor once it set in App.razor?

在我的应用程序中,我打算设置两个布局。 BeforeLoginLayout 和 AfterLoginLayout。截至目前,在 App.Razor 中,我将 defaultLayout 设置为 BeforeLoginLayout。我想在用户登录应用程序后更改默认布局。如何在 Blazor 中执行此操作?我可以在单独的页面中设置它。我想避免这种情况并设置为默认布局。

这里有一些代码和演示页面,展示了如何动态更改布局。您应该能够对此进行调整以满足您的要求。

修改App如下:

<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
    <Found Context="routeData">
        <CascadingValue Value="this">
            <RouteView RouteData="@routeData" DefaultLayout="this.LayoutType" />
        </CascadingValue>
    </Found>
    <NotFound>
        <LayoutView Layout="@typeof(MainLayout)">
            <p>Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {

    private Type LayoutType = typeof(MainLayout);

    public void SetLayout(Type layout)
    {
        if (layout != LayoutType)
        {
            this.LayoutType = layout;
            StateHasChanged();
        }
    }
}

此演示页面随后展示了如何动态更改布局。 OtherLayoutMainLayout 的副本,带有一些区别。

@page "/"

<div class="m-2 p-2">
    <button class="btn btn-secondary" @onclick="() => ButtonClick(typeof(MainLayout))">Main Layout</button>
    <button class="btn btn-dark ms-2" @onclick="() => ButtonClick(typeof(OtherLayout))">Other Layout</button>
</div>


@code {

    [CascadingParameter] public App MyApp { get; set; }


    void ButtonClick(Type layoutType)
    {
        MyApp.SetLayout(layoutType);
    }
}