【问题标题】:How to change the default layout in blazor once it set in App.razor?在 App.razor 中设置后如何更改 blazor 中的默认布局?
【发布时间】:2021-10-27 21:49:07
【问题描述】:

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

【问题讨论】:

    标签: .net-core layout blazor


    【解决方案1】:

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

    修改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:对象引用未设置为对象的实例。
    • 哪个按钮?你创建了OtherLayout吗?
    • 任何按钮。调试时,我可以看到 MyApp 对象为 null。
    • 我的错误。我错过了 App.razor 中的 CascadingValue。现在它起作用了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-06-20
    • 2022-09-27
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2020-01-05
    相关资源
    最近更新 更多