1
votes

I am displaying images inside the list box. Binding the source of the image control using object through datacontext of the listbox.

Problem: I want to display No image (Image) if the url does't have image. Is it possible do it in the xaml code.

Code:

 <ListBox ClipToBounds="False" x:Name="lbBestSellerImage" Width="Auto" 
  ItemsSource="{Binding}" ItemsPanel="{DynamicResource iptListBox}" 
 ItemContainerStyle="{DynamicResource ListBoxItemStyle}" />

 <Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Padding" Value="2,0,0,0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Grid Width="150">
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <Image HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="0" x:Name="img" Source="{Binding ImageUrl}" Height="74" Stretch="Fill" Width="75"/>                                    
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
1
Do you want to display the text No image, or do you just want to have no image?slugster
"No Image" is the text in the image. I want to display this image if there is no image for the item.Geeth

1 Answers

3
votes

The easiest is to create a new value converter that gets passed in the uri and gives back a BitmapImage... It can then decided if the uri is available or not... if it is available, just load the uri into a BitmapImage, else load a default BitmapImage!

public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string uri = (string)value;
        if (string.IsNullOrEmpty(uri))
            return new BitmapImage(new Uri(uriToMyDefaultImage));

        return new BitmapImage(new Uri(uri));

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

The following value converter expects a string that represents a uri to a image... if it is null or empty, a default image is showed, else it just loads the image!