Search code examples
iconsmudblazor

How to bind a MudIcon string to Mud Icon component


<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?


Solution

  • 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