The following code creates a UriToBitmapImage value converter. Simply reference the converter in your databinding and you will be able to data bind an Image control to a URL and have it displayed on your WPF surface.
First, the value converter code:
namespace MyApp.Local
{
public class UriToBitmapImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
BitmapImage image = new BitmapImage();
if (value != null)
{
try
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri((string)value, UriKind.Absolute);
image.EndInit();
}
catch
{
image = null;
}
}
return image;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
}
Add the value converter to your project and compile.
Next, you need to reference the namespace that contains this new class on the WPF Window/Page/Control that you wish to use the converter. (You can also add your converters at the App level.)
xmlns:loc="clr-namespace:MyApp.Local"
I added the UriToBitmapImageConverter class to the MyApp.Local namespace. Thus, I needed to add a reference to the CLR namespace in my XAML in order to use the converter.
Next, you need to add the converter to your XAML page’s resources:
<Page.Resources>
<loc:UriToBitmapImageConverter x:Key="UriToImageConverter" />
</Page.Resources>
Here I used Page.Resources because I am adding this converter to a WPF Page. It would be Window.Resources if you are working with a WPF Window or UserControl.Resources if you are adding this to a UserControl.
Now, simply data bind your image:
<Image Margin="8,7,4,8"
Source="{Binding ImageUri, Converter={StaticResource UriToImageConverter}}"
Stretch="Fill" d:IsHidden="False"/>
In the Source attribute I am data binding a URL / URI which is of type string. This string is then passed through the UriToImageConverter and output is a BitmapImage object that downloads the image dynamically and displays it.
If I have some extra time, or requests, I will build a sample application to demonstrate.