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

如何正确扩展.NET Blazor组件并全局复用?以自定义MudSelect为例

自定义MudBlazor 组件实现方案

核心实现思路

通过继承MudSelect<TValue>创建自定义组件,内置业务模型对应的预选项,预设默认外观属性,同时保留原组件的所有可配置能力,满足你的需求。

自定义组件代码

@inherits MudSelect<TValue>

<!-- 替换为你的业务模型预定义选项 -->
<MudSelectItem Value="BusinessOption.Option1">选项1</MudSelectItem>
<MudSelectItem Value="BusinessOption.Option2">选项2</MudSelectItem>
<MudSelectItem Value="BusinessOption.Option3">选项3</MudSelectItem>

@code {
    protected override void OnInitialized()
    {
        // 设置通用默认外观属性,外部未传入时生效
        if (string.IsNullOrEmpty(Label))
            Label = "请选择";
        if (!Dense.HasValue)
            Dense = false;
        if (!Variant.HasValue)
            Variant = Variant.Outlined;
        
        base.OnInitialized();
    }
}

业务模型示例(枚举为例)

// 你的业务枚举模型
public enum BusinessOption
{
    Option1,
    Option2,
    Option3
}

使用方式

  1. 基础使用(自带默认选项+外观)
<MySelect TValue="BusinessOption" @bind-Value="@SelectedOption" />

@code {
    private BusinessOption SelectedOption { get; set; }
}
  1. 覆盖默认属性
    直接传入MudSelect的常规属性即可覆盖组件默认值:
<MySelect TValue="BusinessOption" @bind-Value="@SelectedOption" Dense="true" Label="业务选项" Variant="Variant.Filled" />

需求匹配说明

  • 需求1:组件内置预定义<MudSelectItem>,继承MudSelect<TValue>后天然支持@bind-Value双向绑定,无需额外配置。
  • 需求2:在OnInitialized中预设了Label、Dense、Variant等默认外观属性,作为组件通用样式。
  • 需求3:所有MudSelect的原生属性都可直接在<MySelect>标签上传入,会自动覆盖组件内部的默认设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:43:21