Articles

Converter: Image path converter

An image converter to convert an empty string (image path) to an "Image not found" image or an image placeholder.

I use it when there is no image specified for my object's ImagePath property. When the ImagePath property is Null or Empty, then it shows an imageplaceholder, retrieved from a staticresource.

using System;
using System.Windows;
using System.Windows.Data;

namespace XpressNetTrainController
{
	public class ImageStringConverter:  IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			var imagePath = (string)value;
			if (!String.IsNullOrEmpty(imagePath))
				return imagePath;

			return Application.Current.Resources["NoImageController"];
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			return null;
		}
	}
}

And in the App.xaml:

<BitmapImage x:Key="NoImageController">Images/LocController/no_image.png</BitmapImage >
<local:ImageStringConverter x:Key="ImageStringConverter" />