Blazor 母版页

什么是母版页

官方示例的 MainLayout.razor 即为母版页;母版页必须继承 LayoutComponentBase,你可以通过继承 LayoutComponentBase 来写自己的母版页

复制代码
@inherits LayoutComponentBase
<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>
    <main>
        <div class="top-row px-4">
            <a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
        </div>
        <article class="content px-4">
            @Body
        </article>
    </main>
</div>
复制代码

母版页可以没有 @Body,但是没有Body就没法为子页面占位

 

如何使用母版页

子页面使用 @layout 来指定母版页

@page "/Index"
@layout MainLayout

<PageTitle>Index</PageTitle>
<h1>我是子页面</h1>

 

全局母版页

在 App.razor 中,为 RouteView 指定默认的 layout,DefaultLayout="@typeof(MainLayout)" ,这样就不用在每个子页面里都专门设置一个母版页了

复制代码
@using BlazorApp1.Pages;
<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
复制代码

以上是官方示例的 App.razor; 也即是说,这里面的 DefaultLayout 实际上是可以不配置的

 

posted @   cchong005  阅读(117)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示