tags:

views:

38

answers:

1

Hi,

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>
+2  A: 

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!

rudigrobler
Thank You for your response. Can you please give sample for this. It will be more helpful for me to continue.
Geetha
The article is now updated
rudigrobler
+1 Either you can use DataTrigger as well.
Avatar
+1 Thank you so much. Working fine.
Geetha