苦苦挣扎于RenderFragement为<T>剃刀基础组件返回细节模板



我尝试实现一个通用的razor基础组件,但在将上下文传递给子组件时无法找到正确的语法。这是我的基类

@typeparam T where T : class
....
<GridColumns>
@Columns
</GridColumns
....
<DetailTemplate>
@Deatil((T) context)
</DetailTemplate>
@code {
protected override RenderFragment Columns { get; }
protected override RenderFragment<T> Detail { get; } 

在派生子元素中我尝试定义这些模板,

protected override RenderFragment Columns
{
get
{
return __builder =>
{
<GridColumn Field="Id" Title="#" />
<GridColumn Field="Name" />
.....
};
}
}

这是工作,但是我不知道如何提供模板的细节

protected override RenderFragment<T> Detail => currentT => __builder =>
{
get             // <== compiler claims a missing ; here
{
return __builder =>
{
if (currentT.ParentId == null)
{
<h1>One</h1>
}
else
{
<h1>Two</h1>
}
};
};
};
谁能给我指个正确的方向?

您不需要使用get,第三个=>隐式地定义了getter。也没有返回值。RenderFragment是一个委托,定义如下:

public delegate void RenderFragment(RenderTreeBuilder builder);

由于没有足够的细节来使用您的代码,这里有一个如何使用Razor标记构建和消费RenderFragment<T>的示例。

@page "/fetchdata"
@using Blazr.Data
@inject WeatherForecastService ForecastService
<PageTitle>Weather forecast</PageTitle>
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from a service.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
@Detail(forecast)
}
</tbody>
</table>
}
@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
}
protected RenderFragment<WeatherForecast> Detail
=> context => __builder =>
{
<tr>
<td>@context.Date.ToShortDateString()</td>
<td>@context.TemperatureC</td>
<td>@context.TemperatureF</td>
<td>@context.Summary</td>
</tr>
};
}

相关内容

  • 没有找到相关文章

最新更新