2010-10-07 40 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