基于相同代码的 2 个不同的 Blazor 页面

Base 2 different Blazor pages on the same code behind

我有一个 Blazor 页面需要在不同情况下以截然不同的方式呈现。我目前正在使用一个非常大的“if”语句来在两者之间做出决定,但它非常笨拙。代码背后有重要的逻辑,我不想 copy/paste。有没有办法让 2 个不同的 UI 页面基于相同的代码?

我试过有 2 个不同的页面隐藏代码,然后继承一个包含所有逻辑的基础 class,就像这样。

public partial class MyPageHorizontal : MyPageLogic
{
}

public partial class MyPageVertical : MyPageLogic
{
}

public partial class MyPageLogic : ComponentBase
{
    //logic and properties go here
}

我收到错误消息“基础 class 与其他部分声明的不同”

你的 Razor 文件需要从你的自定义 Base 继承,就像这样

@inherits IndexBase
@page "/"
@page "/IndexHoriz"

<h1>Hello, world!</h1>

Welcome to your new app.  This page should render horizontally

<SurveyPrompt Title="How is Blazor working for you?" />

否则 Razor 编译器将假设它们继承自 ComponentBase。