<MudIcon Icon="@inboxIcon" Color="Color.Primary" />
@code{
// here this Icon string is coming from database
private string inboxIcon = "Icons.Material.Filled.Inbox";
}
上面的代码没有显示任何图标。如何绑定此图标字符串?
您已接近目标。这样试试:
<MudIcon Icon="@inboxIcon" Color="Color.Primary" />
@code{
// here this Icon string is coming from database
private string inboxIcon = MudBlazor.Icons.Material.Filled.Inbox;
}
命名空间中的Icons
将自动转换为字符串。
此代码没有运行"。。。是在给定上下文中无效的类型";首先,您需要创建一个具有如下类型的Object:private static Icons.Material.Filled iconClass = new Icons.Material.Filled();
你的函数应该是这样得到一个字段:
protected static string GetIconValue(object SourceField, string IconName)
{
string? teste = SourceField?.GetType()?.GetField(IconName)?.GetValue(null)?.ToString();
if (string.IsNullOrEmpty(teste))
{
return @Icons.Material.Filled.Assignment;
}
return teste;
}
老问题,但我也试图从数据库中保存/加载菜单图标,最后使用了反射,就像下面的示例一样。我想使用的所有图标都在icons.Material.Outlined中,所以我只是保存了图标名称";人""Dashboard";,等等(连同Path和Caption(在运行时加载。这个样本可能会让你开始:
@using System.Reflection
<MudNavMenu>
@foreach (var menuitem in MenuItems)
{
<MudNavLink Href="@menuitem" Icon="@GetIconValue(Icons.Material.Outlined, @menuitem)">@menuitem</MudNavLink>
}
</MudNavMenu>
@code {
string[] MenuItems = new string[] {"Dashboard", "Person"};
public static string GetIconValue(object SourceField, string IconName)
{
return SourceField.GetType().GetProperty(IconName).GetValue(SourceField, null).ToString();
}
}
在Mudblazor上运行:https://try.mudblazor.com/snippet/cuQQuplkqVtQpJKV