Search code examples
c#wpfmaterial-design-icons

Dynamic MaterialDesign PackIconKind from config XML in WPF application


I am designing one WPF desktop application where the UI design is totally driven by an configuration file. I have MenuItems which uses MaterialDesign PackIcons. I have the PackIcons mentioned in the config file for each menuitem. e.g.

<MenuItem Name="Menu1">
    ....
    <Icon Type="MaterialDesign">NewBox</Icon>
</MenuItem>
<MenuItem Name="Menu2">
    ....
    <Icon Type="MaterialDesign">ExitToApp</Icon>
</MenuItem>

Now I want to use this icon names while desiging the MenuItems. In XAML I know how to do this

<MenuItem Header="New" Click="MenuItem_NewClick" >
    <MenuItem.Icon>
        <materialDesign:PackIcon Kind="NewBox" />
    </MenuItem.Icon>
</MenuItem>

But I am facing challenge when I am trying to do it via code behind. Normally, we can do this by the following line of code if we have the icon fixed

MenuItem.Icon = new MaterialDesignThemes.Wpf.PackIcon { Kind = MaterialDesignThemes.Wpf.PackIconKind.NewBox};

Can somebody please help me by telling how can I use dynamic icon via code behind?

Thanks


Solution

  • You can use the Enum.Parse or Enum.TryParse method to convert a string value to a PackIconKind, e.g.:

    var kind = (MaterialDesignThemes.Wpf.PackIconKind)Enum
        .Parse(typeof(MaterialDesignThemes.Wpf.PackIconKind), "About");