开发者

WPF - Image control inside Listbox

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"/>
        &l开发者_如何学运维t;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>


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜