2010-10-07 60 views
1

我在列表框中显示图像。通过列表框的datacontext绑定使用对象的图像控件的源代码。WPF - Listbox内部的图像控件

问题:如果url没有图像,我想显示没有图像(图像)。是否有可能在xaml代码中做到这一点。

代码:

<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> 
+0

要显示*文字*'无图像吗?或者您只是想要没有图像吗? – slugster 2010-10-07 05:23:36

+0

“无图像”是图像中的文字。如果项目没有图像,我想显示此图像。 – Geeth 2010-10-07 05:37:39

回答

3

最简单的是创建得到的URI通过了一项新的值转换器,并给出回来的BitmapImage ......然后它可以决定如果URI是否可用?如果可用,只需将uri加载到BitmapImage中,否则加载默认的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(); 
    } 
} 

以下值转换器预计,代表一个URI到图像的字符串...如果它为null或空,默认的图像显示,否则它只是加载图像!

+0

感谢您的回复。你能举个样品吗?这对我继续会更有帮助。 – Geeth 2010-10-07 06:03:39

+0

文章现在已更新 – rudigrobler 2010-10-07 06:28:04

+0

+1您也可以使用DataTrigger。 – 2010-10-07 07:01:48