You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于字典实现ASP.NET Core Blazor templated components模板组件

.NET 5 Blazor 字典类型模板组件实现方案

1. 创建通用字典模板组件

新建名为DictionaryTemplate.razor的Razor组件,代码如下:

@typeparam TKey
@typeparam TValue

@if (DataSource == null || !DataSource.Any())
{
    @EmptyTemplate
}
else
{
    @HeaderTemplate
    @foreach (var item in DataSource)
    {
        @ItemTemplate(item)
    }
}

@code {
    /// <summary>
    /// 绑定的字典数据源
    /// </summary>
    [Parameter]
    public Dictionary<TKey, TValue> DataSource { get; set; }

    /// <summary>
    /// 字典单条数据的渲染模板
    /// </summary>
    [Parameter]
    public RenderFragment<KeyValuePair<TKey, TValue>> ItemTemplate { get; set; }

    /// <summary>
    /// 列表头部渲染模板
    /// </summary>
    [Parameter]
    public RenderFragment HeaderTemplate { get; set; } = new(builder => { });

    /// <summary>
    /// 无数据时的渲染模板
    /// </summary>
    [Parameter]
    public RenderFragment EmptyTemplate { get; set; } = new(builder => { });
}

2. 父组件调用示例

在需要使用该模板的页面/组件中,按如下方式调用:

@page "/testdictionary"

<h2>模板组件测试页</h2>

<DictionaryTemplate DataSource="@ProductStock" Context="stockItem">
    <HeaderTemplate>
        <div class="mb-2 font-weight-bold">产品库存清单</div>
        <hr />
    </HeaderTemplate>
    <ItemTemplate>
        <div class="row mb-1">
            <div class="col-6">产品名称:@stockItem.Key</div>
            <div class="col-6">库存数量:@stockItem.Value</div>
        </div>
    </ItemTemplate>
    <EmptyTemplate>
        <p class="text-muted">当前没有库存数据</p>
    </EmptyTemplate>
</DictionaryTemplate>

@code {
    // 测试用字典数据源
    private Dictionary<string, int> ProductStock { get; set; } = new()
    {
        {"机械键盘", 27},
        {"无线鼠标", 63},
        {"27寸显示器", 14},
        {"外接硬盘", 32}
    };
}

3. .NET 5适配注意事项

  • 泛型参数可由传入的DataSource自动推断,无需手动声明,若出现类型推断失败的情况,可手动指定类型参数:<DictionaryTemplate TKey="string" TValue="int" DataSource="@ProductStock">
  • 若字典的TValue为自定义类,可直接在ItemTemplate中访问该类的属性,例如@stockItem.Value.ProductPrice
  • 可根据需求拓展更多模板参数,例如添加FooterTemplate实现列表底部渲染逻辑

内容的提问来源于stack exchange,提问作者josh139

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 09:45:03