2012-02-21 76 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