I have a wpf ListBox, and each item has an image that the list needs to download from a server - the list definition looks like so:
<ListBox x:Name="List" BorderThickness="0" AlternationCount="2" ItemContainerStyle="{StaticResource alternatingWithBinding}"
HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="itemsGrid" Margin="3" ShowGridLines="False" >
<Grid.RowDefinitions>
<RowDefinition Height="59"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="45" />
<ColumnDefinition Width="60" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Button x:Name="btn" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" Tag="{Binding}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" />
<Image x:Name="Thumb" Grid.Column="1" Stretch="Uniform" Opacity="1.0" Source="{Binding Path=Image, Converter={StaticResource ImageConverter}}" Height="65" VerticalAlignment="Center"/>
<TextBlock x:Name="Name" Grid.Column="2" Padding="2" Margin="17,0" VerticalAlignment="Center" Text="{Binding Path=Name}"
Tag="{Binding}" />
</Grid>
<DataTemplate.Triggers>
...
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
and the converter looks like:
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
{
value = new Uri((string)value);
}
if (value is Uri)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = 150;
bi.UriSource = value;
bi.DownloadFailed += new EventHandler<ExceptionEventArgs>(bi_DownloadFailed);
bi.EndInit();
return bi;
}
return null;
}
The idea is to show a default image when the sourceUrl returns nothing from the server. But since i'm using the converter in the XAML code,
Source="{Binding Path=Image, Converter={StaticResource ImageConverter}}"
I'm not sure how to intercept that case. I see that BitmapImage has the DownloadFailed event which is perfect for me, I just don't know how to use that in this context.