2013-11-20 171 views
0

我正在使用BindingImage.SourcePropertybyte[]变量。在IValueConverter我检查是否value.Length > 0,如果是的话,我从它的值设置来源。然后我需要知道,如果它已设置,那么我可以显示或隐藏清除按钮。 Image.Source总是不为空。如何知道,如果它是从byte[]数组中设置的? 我的代码:检查ImageSource是否为空

var bnd = new Binding 
{ 
    Mode = BindingMode.TwoWay, 
    Path = new PropertyPath("DataPath.Value"), 
    Converter = new ByteToImageConverter() 
}; 
myImage.SetBinding(Image.SourceProperty, bnd); 

public class ByteToImageConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     var val = value as byte[]; 
     var bmp = new BitmapImage(); 
     if (val.Length > 0) { 
      bmp.SetSource(new MemoryStream(val)); 
     } 
     return bmp; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value == null) { 
      return new byte[0]; 
     } 
     var ms = new MemoryStream(); 
     var bmp = new WriteableBitmap(value as BitmapSource); 
     bmp.SaveJpeg(ms, 150, 200, 0, 100); 
     return ms.ToArray(); 
    } 
} 

现在我需要的代码检查,如果图像信号源属性设置:

// myImage.Source always != null even if there was no bmp.SetSource() call 
var str = myImage.Source != null ? "Image is set" : "Image is empty"; 
+0

灿你请澄清你的问题?我不确定我了解你的情况是什么? –

回答

0

类似的东西

if (((BitmapImage)myImage.Source).UriSource == null) 
{ 
//Image is empty 
} 

var str = ((BitmapImage)myImage.Source).UriSource != null ? "Image is set" : "Image is empty";