2

Does anyone know how to bind a byte[] (image) to a Image control in a axml view. My ViewModel inherit from MvxViewModel. All my other bindings works great but I cannot find a way to bind that image.

2 Answers 2

4

You can do it even easier and I also found that out after stumbling on that question:

As the Android-binding for setting a Bitmap for a ImageView is Bitmap (as you can see at [1]), you can configure your view like this:

    <ImageView
        local:MvxBind="Bitmap ByteArrayToImage(ImageByteArray)" />

Then you only need to define a ValueConverter, called ByteArrayToImageValueConverter, that converts the byte array to an instance of Bitmap. For me, using a ValueConverter is the preferred way over creating custom binding ;)

You already had the code for converting a byte array to a bitmap: BitmapFactory.DecodeByteArray(_rawImage, 0,_rawImage.Length);

[1] https://github.com/MvvmCross/MvvmCross/blob/bbf9a2ac76e74d9404f4b57036c6e29dfe2cc6c3/Cirrious/Cirrious.MvvmCross.Binding.Droid/MvxAndroidBindingBuilder.cs#L79

1
  • Beautiful solution. Thanks! Feb 24, 2016 at 10:09
2

I think you could bind this using a custom UI control.

To do this, you'll need to do something like:

  1. inherit a new MyImageView from ImageView
  2. add the default constructor (which passes the context and attributes down to the base constructor)
  3. add a new RawImage property to MyImageView, implementing it as:

    private byte[] _rawImage;
    public byte[] RawImage
    {
         get { return _rawImage; }
         set 
         {
                 _rawImage = value;
                 if (_rawImage == null)
                         return;
    
                 var bitmap = BitmapFactory.DecodeByteArray(_rawImage, 0,_rawImage.Length);
                 SetImageBitmap(bitmap);
         }
    }
    

You can then use that MyImageView control in your axml instead of the normal ImageView.

Note - this code above not tested - but once you get the byte[] in the View I'm sure you'll work out what Droid code to use.


As an alternative approach to this, you could also use a custom binding to bind a byte[] to a normal ImageView - see an example of custom binding in In MvvmCross how do I do custom bind properties

1
  • I used the custom binding in the end. Thank you for your help Jan 8, 2013 at 2:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.