I'm trying to bind a list of custom objects to a WPF Image like this:
<Image>
<Image.Source>
<BitmapImage UriSource="{Binding Path=ImagePath}" />
</Image.Source>
</Image>
But it doesn't work. This is the error I'm getting:
"Property 'UriSource' or property 'StreamSource' must be set."
What am I missing?
WPF has built-in converters for certain types. If you bind the Image's Source
property to a string
or Uri
value, under the hood WPF will use an ImageSourceConverter to convert the value to an ImageSource
.
So
<Image Source="{Binding ImageSource}"/>
would work if the ImageSource property was a string representation of a valid URI to an image.
You can of course roll your own Binding converter:
public class ImageConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return new BitmapImage(new Uri(value.ToString()));
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
and use it like this:
<Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/>
This article by Atul Gupta has sample code that covers several scenarios:
You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it
<Image Width="90" Height="90"
Source="{Binding Path=ImageSource}"
Margin="0,0,0,5" />
And the class property is simply this
public object ImageSource {
get {
BitmapImage image = new BitmapImage();
try {
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri( FullPath, UriKind.Absolute );
image.EndInit();
}
catch{
return DependencyProperty.UnsetValue;
}
return image;
}
}
I suppose it may be a little more work than the value converter, but it is another option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With