C# Binding to Images in WPF
To bind to in image in WPF we need to be able to convert the Path to the .PNG file (or other type) to a Bitmap, this is done via an on the fly convertor.
<Image
x:Name="Img_SimpleNotification"
Source="{Binding SimpleNotificationImagePath,Converter={StaticResource StringtoBitmapSourceConvertor}}"
Height="100"
Width="100"
Margin="10,10,10,10">
</Image>To make this work in the WPF XAML we must add a new namespace reference pointed at the name space where the convertor class resides.
xmlns:CustomConvertors ="clr-namespace:UI_Catalog.Convertors"
And in addition we must also specify a resource for the convertor.
<Window.Resources>
<ResourceDictionary>
<CustomConvertors:StringtoBitmapSourceConvertor x:Key="StringtoBitmapSourceConvertor"></CustomConvertors:StringtoBitmapSourceConvertor>
</ResourceDictionary>
</Window.Resources> The convertor takes in the image file path as a string and will return a Bitmap.
using System;
using System.Drawing;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
namespace StandardHolesUserInterface.Convertors
{
public class StringtoBitmapSourceConvertor : IValueConverter
{
public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value is string)
{
string Path = (string)value;
return Imaging.CreateBitmapSourceFromHBitmap(
((Bitmap)Bitmap.FromFile(Path, true)).GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}Within the View Model (Data Context) we can then create a string property that is valuated by a path to a image in this case a PNG file, remembering we must implement ‘INotifyPropertyChanged’ within the View Model or within an inherited View Model Base.
string _SimpleNotificationImagePath;
public string SimpleNotificationImagePath
{
get => _SimpleNotificationImagePath;
set { _SimpleNotificationImagePath = value; NotifyPropertyChanged(); }
}
switch (warningType)
{
case WaringType.Error:
SimpleNotificationImagePath = @"./Images/Error.png";
break;
case WaringType.Information:
SimpleNotificationImagePath = @"./Images/Info.png";
break; ;
default:
SimpleNotificationImagePath = @"./Images/Warning.png";
break;
}