I am trying to accomplish this: Add a Image in the DataGridTemplateColumn but instead of Image use materialDesign:PackIcon. Here is my code.
<DataGridTemplateColumn Header="Message">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<materialDesign:PackIcon Kind="{Binding MsgStatus,Converter={StaticResource NumberToIconConverter}}" Foreground="Green"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
MsgStatus is the column value, depending on its value the icon will be different. This is accomplished through a converter which returns IconKind.
public class NumberToIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string input = value as string;
switch (input)
{
case "1":
return MaterialDesignThemes.Wpf.PackIconKind.Alarm;
case "2":
return MaterialDesignThemes.Wpf.PackIconKind.Message;
default:
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Converter is referenced in the usercontrol but it seems that is never called and there is no errors during debugging or execution.
<UserControl.Resources>
<local:NameToBrushConverter x:Key="NumberToIconConverter"/>
</UserControl.Resources>
Using the same binding with other converters on the same column with Image or textblock (e.g.) works but with materialDesign:PackIcon the converter is never called and thus, icons don't change. Am I wrong with the binding?
EDIT:
Solved: Converter was not being called, replaced reference with:
<UserControl.Resources>
<local:NumberToIconConverter x:Key="NumberToIconConverter"/>
</UserControl.Resources>
Converter using answer, added DBNull check to avoid Null Exception:
public class NumberToIconConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == DBNull.Value)
{
return DependencyProperty.UnsetValue;
}
var input = System.Convert.ToInt16(value);
switch (input)
{
case 1:
return MaterialDesignThemes.Wpf.PackIconKind.Alarm;
case 2:
return MaterialDesignThemes.Wpf.PackIconKind.Message;
default:
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}