检查ImageSource是否为空

时间:2013-11-20 11:14:58

标签: c# binding windows-phone

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

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();
    }
}

现在我需要检查代码,如果设置了image source属性:

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

1 个答案:

答案 0 :(得分:0)

类似的东西

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

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