Introduction
The Image
control in WPF takes as source a URL of an image or a BitmapImage
which contains a URL within. In this article, I will present a way to bind an Image
class object (which does not contain an image URL) directly to an Image
control source.
Using the Code
I won't talk about the conversion itself from Image
to BitmapImage
as we can find samples for it over the web easily (e.g. here). The idea here is to use a converter which will accept as value an Image
from the binding, convert it to BitmapImage
and return it to the Image
control source property.
For this, we need to setup an IValueConverter
that will get a value which will be of type Image
and convert it to BitmapImage
like this:
public class ImageToSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Image image = value as Image;
if (image != null)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, image.RawFormat);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
return bi;
}
return null;
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
In the code behind, you will have something like this:
public Image UserImage
{
get
{
return _model.UserImage;
}
}
And in the XAML, you will bind them directly like this:
<converters:ImageToSourceConverter x:Name="ImageToSourceConverter"/>
...
<Image source="{Binding Path=UserImage, Converter={StaticResource ImageToSourceConverter}" />
And by that, the binding is direct between the Image
and the source of the Image
control.
Points of Interest
At first, I did the simple thing of converting in the viewmodel and then bind the source to an object of type BitmapImage
. Once I needed it the second time in another viewmodel, it was clear I needed to do something else, and a converter was the best solution.