Each time I have the need for an image converter for a WPF application, I end up searching the web looking for a sample, so this time, I’m putting a sample somewhere I can find it again easily. Below is a basic IValueConverter implementation to convert a file name into a BitmapImage located in an images folder.
Code for Sample Project
public class IconImageConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
// if value isn't null, we can safely do the conversion.
if (value != null)
{
string imageName = value.ToString();
Uri uri = new Uri(String.Format("/Images/{0}", imageName),
UriKind.Relative);
return new BitmapImage(uri);
}
return null;
}
public object ConvertBack(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}