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

5
在我的应用程序中,我计划设置两个布局。BeforeLoginLayout和AfterLoginLayout。目前,在App.Razor中,我将defaultLayout设置为BeforeLoginLayout。我想在用户登录应用程序后更改默认布局。如何在Blazor中实现此操作?我可以在单个页面上进行设置。我想避免这种情况,并将其设置为默认布局。
1个回答

8

这里有一些代码和演示页面,展示了如何动态更改布局。您应该能够根据自己的需求进行调整。

按照以下方式修改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);
    }
}

我在按钮点击时遇到了这个错误。Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]未处理的异常呈现组件:对象引用未设置为对象的实例。 System.NullReferenceException:对象引用未设置为对象的实例。 - Aneez Azeez
哪个按钮?你创建了 OtherLayout 吗? - MrC aka Shaun Curtis
任何按钮。当我进行调试时,我可以看到MyApp对象为空。 - Aneez Azeez
我的错误。我在App.razor中错过了CascadingValue,现在它可以正常工作了。谢谢。 - Aneez Azeez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接