Scott Nimrod
Scott Nimrod

Reputation: 11570

How can I databind an image?

How can I databind an image using XAML?

Specifically, I have a stream object that I would like to convert into an image.

However, I just cannot find a basic example of how to do this.

1. What does the viewmodel property look like?

2. What does the XAML look like?

Upvotes: 1

Views: 4308

Answers (2)

Pete
Pete

Reputation: 4746

The demo illustrates the binding via code. For a XAML implementation you need something along the lines of:-

<Image Source="{Binding MyImageAsBytes, Converter={StaticResource MyByteToImageSourceConverter}}" />

Once you have your byte[] in your ViewModel, you will need a converter to convert this byte array, that contains the image, to a Xamarin.Forms ImageSource.

The converter, takes the byte[] array and converts to an ImageSource via:-

objImageSource = ImageSource.FromStream(() => new MemoryStream(bytImageData));

Example:-

StackLayout objStackLayout = new StackLayout();

byte[] bytImage = { your image as a byte collection }

this.BindingContext = new MyImageViewModel()
{
    MyImageAsBytes = bytImage
};

Image objImage = new Image();
objImage.SetBinding(Image.SourceProperty, "MyImageAsBytes", converter: new MyByteToImageSourceConverter());

objStackLayout.Children.Add(objImage);

ViewModel:-

public class MyImageViewModel
    : Xamarin.Forms.View
{
    public static readonly BindableProperty MyImageAsBytesProperty = BindableProperty.Create<MyImageViewModel, byte[]>(p => p.MyImageAsBytes, default(byte[]));

    public byte[] MyImageAsBytes
    {
        get { return (byte[])GetValue(MyImageAsBytesProperty); }
        set { SetValue(MyImageAsBytesProperty, value); }
    }
}

Converter:-

public class MyByteToImageSourceConverter
    : IValueConverter
{
    public object Convert(object pobjValue, Type pobjTargetType, object pobjParameter, System.Globalization.CultureInfo pobjCulture)
    {
        ImageSource objImageSource;
        //
        if (pobjValue != null)
        {
            byte[] bytImageData = (byte[])pobjValue;
            //
            objImageSource = ImageSource.FromStream(() => new MemoryStream(bytImageData));
        }
        else
        {
            objImageSource = null;
        }   
        //
        return objImageSource;
    }

    public object ConvertBack(object pobjValue, Type pobjTargetType, object pobjParameter, System.Globalization.CultureInfo pobjCulture)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 2

Jason
Jason

Reputation: 89214

Forms has a StreamImageSource you can use to do this. However, I don't think you can use it in XAML without writing a custom converter. To use it in code, you would do something like this:

image1.Source = ImageSource.FromStream(() =>
{
  // whatever you need to do to create your stream
  return stream;
});

Upvotes: 3

Related Questions