如何在MudBlazor项目中创建类使用自定义SVG图标?
在MudBlazor中使用自定义SVG图标(类名调用方式)
以下是实现像内置图标那样通过类名调用自定义SVG的具体步骤:
1. 优化SVG代码
先处理你下载的SMS图标,移除不必要的属性(比如width、height、class、version),保留xmlns、viewBox和路径内容,这样MudBlazor可以自动适配图标大小和主题颜色。优化后的代码如下:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"> <path d="M789.333333 832H234.666667l-128 128V234.666667c0-70.4 57.6-128 128-128h554.666666c70.4 0 128 57.6 128 128v469.333333c0 70.4-57.6 128-128 128z" fill="#009688" /> <path d="M512 469.333333m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" fill="#FFFFFF" /> <path d="M725.333333 469.333333m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" fill="#FFFFFF" /> <path d="M298.666667 469.333333m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" fill="#FFFFFF" /> </svg>
如果想让图标颜色跟随MudBlazor主题,可将fill属性改为currentColor,图标会自动继承父元素的文字颜色。
2. 创建自定义图标静态类
在项目中新建一个静态类(比如MyIcons.cs),把优化后的SVG字符串作为静态属性存放,模拟内置图标结构:
namespace YourProjectNamespace; public static class MyIcons { public static class Custom { public const string SMS = @"<svg xmlns=""http://www.w3.org/2000/svg"" viewBox=""0 0 1024 1024""> <path d=""M789.333333 832H234.666667l-128 128V234.666667c0-70.4 57.6-128 128-128h554.666666c70.4 0 128 57.6 128 128v469.333333c0 70.4-57.6 128-128 128z"" fill=""#009688"" /> <path d=""M512 469.333333m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z"" fill=""#FFFFFF"" /> <path d=""M725.333333 469.333333m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z"" fill=""#FFFFFF"" /> <path d=""M298.666667 469.333333m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z"" fill=""#FFFFFF"" /> </svg>"; } }
注:字符串中的双引号需转义为"",或使用C#逐字字符串(@前缀)避免转义。
3. 在组件中调用自定义图标
现在你可以像使用内置图标一样,通过类名引用自定义图标:
<MudIconButton Icon="@MyIcons.Custom.SMS" Disabled="false" aria-label="send sms" />
额外技巧:全局注册图标(可选)
如果想更贴近内置图标的调用方式,可将图标注册到MudBlazor的图标提供器中:
- 在
Program.cs中添加注册代码:
builder.Services.AddMudServices(config => { // 注册自定义图标 config.IconProvider.RegisterIcons(new Dictionary<string, string> { { "Custom.SMS", MyIcons.Custom.SMS } }); });
- 调用时直接用字符串引用:
<MudIconButton Icon="Custom.SMS" aria-label="send sms" />
内容的提问来源于stack exchange,提问作者ani H
相关产品推荐
相关产品推荐

