2012-02-21 80 views
0

我有一個List<Employee>。每個員工都有一個存儲圖片的字節[](或null)。我需要以某種方式將此字節數組綁定到我正在使用的內容模板上的圖像控件,或者如果員工沒有圖片,我想顯示本地jpg文件。我想到的方式是定義一個轉換器,它將返回BitmapImage(GetImageFromByteArray()方法的返回類型)或字符串(文件名的路徑)。這顯然意味着此方法能夠返回兩種類型,但我不會認爲這是一個問題,看起來好像我已經指定返回類型爲對象。轉換器返回不同類型?

總之,這裏是我的C#:

public class GuidToImageConverter : IValueConverter 
     { 
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
      { 
       Guid id = new Guid(value.ToString()); 
       Employee employee = Employees.SingleOrDefault(o => o.Id.Equals(id)); 
       return employee.Picture != null ? GetImageFromByteArray(employee.Picture) : "/Resource/images/silhouette.jpg"; 
      } 

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

而在XAML中使用像這樣:

<local:GuidToImageConverter x:Key="GuidToImageConverter"/> 

    <local:OrientedGroupHeaderContentTemplateSelector x:Key="GroupHeaderContentTemplateSelector"> 
     <!-- Default templates: --> 
     <local:OrientedGroupHeaderContentTemplateSelector.HorizontalMonthViewDateTemplate> 
      <DataTemplate> 
       <Image Width="60" Height="60" Margin="5 0 10 0" HorizontalAlignment="Left" Stretch="UniformToFill" Source="{Binding Path=Name.Id, Converter={StaticResource GuidToImageConverter}, ConverterParameter=1}" /> 
      </DataTemplate> 
     </local:OrientedGroupHeaderContentTemplateSelector.HorizontalMonthViewDateTemplate> 
    </local:OrientedGroupHeaderContentTemplateSelector> 

錯誤:

「錯誤1 - 條件表達式的類型無法確定因爲'System.Windows.Media.Imaging.BitmapImage'和'string'之間沒有隱式轉換「」

我知道如果有適當的MVVM結構,這可能不會成爲問題,但目前不可能改變這一切。

回答

4

改變返回語句來此,使其工作:

if(employee.Picture != null) 
    return GetImageFromByteArray(employee.Picture) 
return "/Resource/images/silhouette.jpg"; 

或者你可以先創建從「默認圖像」的圖像,然後就可以像以前一樣使用return語句。

+1

+1:你說得對,他的問題與WPF或轉換器無關。 – 2012-02-21 08:53:41

+0

「或者你可以先從'默認圖像'創建一個圖像,然後像以前一樣使用return語句。」沒想到這個。非常感謝。我會嘗試重新構造返回語句,就像您先建議的那樣。 – 2012-02-21 08:56:03

+1

工作。謝了哥們。 – 2012-02-21 08:57:07