Windows Phone 8中的绑定图像

时间:2013-09-18 17:39:54

标签: image xaml windows-phone-7 binding windows-phone-8

我可以将图像绑定到xaml而无需使用图像源(主要方法)(在xaml页面中):

<Image Height="170" Width="220" Source="{Binding Source=Img}" ></Image>

因为我有从字节数组转换的图像,并且没有任何名称或来源。 像这里:

Image Img = new Image();
Img=ByteArraytoBitmap(ob0[0].Img.ToArray());

public BitmapImage ByteArraytoBitmap(Byte[] byteArray)
{
    MemoryStream stream = new MemoryStream(byteArray);
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.SetSource(stream);
    return bitmapImage;
}

1 个答案:

答案 0 :(得分:1)

你可以在你的对象上添加一个BitmapImage属性(ob0 [0]的类),然后可以直接将位图图像绑定到图像的源(注意绑定应该是Source="{Binding Img} “而不是Source="{Binding Source=Img}"

另一个解决方案是你创建一个附加属性,这样的东西应该工作:

public class MyAttachedProperty
{
    public static readonly DependencyProperty ByteArraySourceProperty =
        DependencyProperty.RegisterAttached("ByteArraySource", typeof (Byte[]), typeof (MyAttachedProperty), new PropertyMetadata(default(Byte[],byteArraySource)))

        private static void byteArraySource(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Image img = d as Image;
            if (e.NewValue != null)
            {
                img.Source = ByteArraytoBitmap((Byte[]) e.NewValue);
            }
        }

    public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
    {
        MemoryStream stream = new MemoryStream(byteArray);
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.SetSource(stream);
        return bitmapImage;
    }

    public static void SetByteArraySource(UIElement element, Byte[] value)
    {
        element.SetValue(ByteArraySourceProperty, value);
    }

    public static Byte[] GetByteArraySource(UIElement element)
    {
        return (Byte[]) element.GetValue(ByteArraySourceProperty);
    }
}

然后进行绑定你可以像这样使用它:

<Image Height="170" Width="220" local:MyAttachedProperty.ByteArraySource="{Binding Img}" ></Image>