Reputation: 23
<MudIcon Icon="@inboxIcon" Color="Color.Primary" />
@code{
// here this Icon string is coming from database
private string inboxIcon = "Icons.Material.Filled.Inbox";
}
the above code is is not displaying any icon. How to bind this Icon string?
Upvotes: 2
Views: 3821
Reputation: 41
@using System.Reflection
@using MudBlazor
<MudNavMenu>
@foreach (var item in MenuItems)
{
<MudNavLink Href="@item" Icon="@GetIconValue(typeof(Icons.Material.Outlined), @item)">@item</MudNavLink>
}
</MudNavMenu>
@code {
string[] MenuItems = { "Dashboard", "Person" };
public string GetIconValue(Type source, string IconName)
{
//reflecting method for getting dynamic mudblazor icons
try
{
var member = source.GetMember(IconName).First();
if (member is PropertyInfo property)
{
// If the member is a property, get its value
return property.GetValue(null)?.ToString();
}
else if (member is FieldInfo field)
{
// If the member is a field or a constant, get its value
return field.GetValue(null)?.ToString();
}else{
//default icon
return Icons.Material.Outlined.Login;
}
}
catch (Exception)
{
//default icon
return Icons.Material.Outlined.Login;
}
}
}
Run on mudBlazor https://try.mudblazor.com/snippet/cEwIEpcrCIWkHFoS
Upvotes: 1
Reputation: 31
This code didn't run "...is a type, which is not valid in the given context"
First you need to create an Object with that type like this:
private static Icons.Material.Filled iconClass = new Icons.Material.Filled();
and your function should be like this to get a field:
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;
}
Upvotes: 3
Reputation: 14
Old question, but I was also trying to save/load menu icons from the database, and wound up using reflection like the sample below. All the icons I wanted to use were in Icons.Material.Outlined, so I'm just saving the icon name "Person", "Dashboard", etc. (Along with Path and Caption) to load at runtime. This sample might get you going:
@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();
}
}
Run on Mudblazor: https://try.mudblazor.com/snippet/cuQQuplkqVtQpJKV
Upvotes: -1
Reputation: 86
You are nearly there. Try it like this:
<MudIcon Icon="@inboxIcon" Color="Color.Primary" />
@code{
// here this Icon string is coming from database
private string inboxIcon = MudBlazor.Icons.Material.Filled.Inbox;
}
The Icons
in the namespace will be automatically converted into a string.
Upvotes: 5