Wednesday, September 3, 2008

Silverlight/WPF: Returning Image Data from a Converter


Recently, when working with a class that implemented IValueConverter, I encountered some behavior I found unintuitive when returning an image URI value from the Convert() method. My Convert() method was returning a URI string as the Source value for an Image XAML element. This worked on the initial load, but never on reloading the DataContext. I found that in order for the image to change when the DataContext changes, the Converter must return a new BitmapImage as the Source value for the Image XAML element.

For an introduction to IValueConverter, check out this blog post.

My Converter was set up to examine the DataContext of the parent control, and return a specific image depending on settings in the DataContext. The XAML for the image looks like this:

<Image x:Name="frontImage" Source="{Binding Converter={StaticResource ThumbnailImageConverter}}" />
The abridged code for the original converter class appears below:
public class ThumbnailImageConverter : IValueConverter{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Show)
{
Show show = (Show)value;
if ((show == null) || (!show.CanPlay))
{
//No video
return "/Images/NoVideo.png";
}
else
{
//Video available
return "/Images/VideoAvailable.png";
}
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion}


However, I found that when the DataContext for the Image's parent control changed, the image would never change over to the correct value. The change only seems to get picked up when the Converter returns a new Bitmap, as shown below:


if ((show == null) || (!show.CanPlay))
{
//No video
return new BitmapImage(new Uri("/Images/NoVideo.png", UriKind.Relative)); }else{
//Video Available
return new BitmapImage(new Uri("/Images/VideoAvailable.png", UriKind.Relative));
}

1 comment:

  1. Everyone people day cash overhauls at interims Il offers many credit alternatives for staying sharp at the side of, day cash updates, Salary day and Size Use cured bank credits, at the side of Automobile started Use cured cash advances jackson-MS bank advances. Totally different people target serving to you decide on for the correct advance item aside from to item and administrations to assist you to satisfy your low worth desires.

    ReplyDelete

Note: Only a member of this blog may post a comment.