title: Xamarin binding Image as binary array within a ListView. Issue while removing entries from the observable collection
body: <p>I have a xamarin android app which provides the option to make images. Those images will be stored into a database. The existing images will be displayed in a list view (as a preview). You need to be able to delete those images. Everything works fine except the image "removal".
  I am binding the images via ObservableCollection. Each object has a binary array property named "ImageDocumentData". This property will be used as binding for the "Image.Source". I am using a converter for the binding in order to convert the binary array into a ImageSource (via MemoryStream).
  It does display everything correctly. However if I have more than one image in the preview listview and I start remove images from the ObservableCollection I am getting the runtime error:</p>
  
  <blockquote>
    <p>System.ObjectDisposedException: 'Cannot access a closed Stream.'</p>
  </blockquote>
  
  <p>While rearranging the listview ui during runtime he is not getting into the converter functions again. 
  I am suspecting the following:
  Each time after adding a new image to the ObservableCollection, the image control is disposing the ImageSource stream. After I remove an entry from the ObservableCollection, he is taking the internal cached ImageSource Object and is trying to read from the same stream again which he already disposed. He needs to get the Image Data again because after I delete an entry from the collection he needs to rearranging (redraw) the listview.
  I really don't know how to solve that issue. I need to use a stream within the image source because I only have a binary array (no file, no uri possible).
  This is only my assumption. However I can't see any other reasonable explanation for this runtime error. I've tried a few other options but so far none have worked for me, so I was hoping someone here can give me a hint into the correct direction.</p>
  
  <p>This is my DTO:</p>
  
  <pre><code>    [DataContract]
      public class RequestItemImageDocument : INotifyPropertyChanged
      {
  
          #region Fields
          private Guid _requestItemImageDocId;
          private Guid _orderItemId;
          private byte[] _imagedocData;
          private string _documentDescription;
          private DateTime? _storageDate;
          private byte _isSynced;
          #endregion
  
          #region Properties
          [DataMember]
          public Guid RequestItemImageDocumentId 
          {
              get 
              {
                  return _requestItemImageDocId;
              }
              set 
              {
                  _requestItemImageDocId = value;
                  if (PropertyChanged != null)
                      PropertyChanged(this, new PropertyChangedEventArgs("RequestItemImageDocumentId"));
              } 
          }
          [DataMember]
          public Guid OrderItemId 
          {
              get
              {
                  return _orderItemId;
              }
              set
              {
                  _orderItemId = value;
                  if (PropertyChanged != null)
                      PropertyChanged(this, new PropertyChangedEventArgs("OrderItemId"));
              }
          }
  
          [DataMember]
          public byte[] ImageDocumentData 
          {
              get
              {
                  return _imagedocData;
              }
              set
              {
                  _imagedocData = value;
                  if (PropertyChanged != null) 
                  {
                      PropertyChanged(this, new PropertyChangedEventArgs("ImageDocumentData"));
  
                  }
              }
          }
          [DataMember]
          public string DocumentDescription 
          {
              get
              {
                  return _documentDescription;
              }
              set
              {
                  _documentDescription = value;
                  if (PropertyChanged != null)
                      PropertyChanged(this, new PropertyChangedEventArgs("DocumentDescription"));
              }
          }
          [DataMember]
          public DateTime? StorageDate 
          {
              get
              {
                  return _storageDate;
              }
              set
              {
                  _storageDate = value;
                  if (PropertyChanged != null)
                      PropertyChanged(this, new PropertyChangedEventArgs("StorageDate"));
              }
          }
          [DataMember]
          public byte IsSynced 
          {
              get
              {
                  return _isSynced;
              }
              set
              {
                  _isSynced = value;
                  if (PropertyChanged != null)
                      PropertyChanged(this, new PropertyChangedEventArgs("IsSynced"));
              }
          }
          #endregion
          #region Constr
          public RequestItemImageDocument() 
          {
  
          }
          #endregion
          public event PropertyChangedEventHandler PropertyChanged;
      }
  </code></pre>
  
  <p>This is my view:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt;
  &lt;ui:PasAMBasePage
      x:Class="AssetManagement.Mobile.Core.UI.OrderItemImageDocumentationPage"
      xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      xmlns:actionMenu="clr-namespace:Client.ApplicationDataModel.UI.Controls.ActionMenu;assembly=Client.ApplicationDataModel.UI"
      xmlns:controls="clr-namespace:AssetManagement.Mobile.Core.Controls"
      xmlns:controls1="clr-namespace:UI.XF.Controls;assembly=UI"
      xmlns:AppList="clr-namespace:Client.ApplicationDataModel.UI.Controls.AppList;assembly=Client.ApplicationDataModel.UI"
      xmlns:res="clr-namespace:AssetManagement.Mobile.Core.Resources"
      xmlns:ui="clr-namespace:AssetManagement.Mobile.Core.UI"
      xmlns:valueconverter="clr-namespace:AssetManagement.Mobile.Core.Classes.ValueConverter"
      xmlns:viewmodel="clr-namespace:AssetManagement.Mobile.Core.ViewModels"
      Title="Bild Dokumentation" 
      x:TypeArguments="viewmodel:OrderItemImageDocuViewModel"&gt;&lt;!--{res:Translate OrderItemImageDocumentary}--&gt;
      &lt;Grid&gt;
          &lt;Grid.RowDefinitions&gt;
              &lt;RowDefinition Height="*" /&gt;
              &lt;RowDefinition Height="Auto" /&gt;
          &lt;/Grid.RowDefinitions&gt;
          &lt;Grid.ColumnDefinitions&gt;
              &lt;ColumnDefinition Width="Auto" /&gt;
              &lt;ColumnDefinition Width="*" /&gt;
              &lt;ColumnDefinition Width="Auto" /&gt;
          &lt;/Grid.ColumnDefinitions&gt;
          &lt;StackLayout Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3"&gt;
              &lt;ListView ItemsSource="{Binding OrderItemImages}"
            HasUnevenRows="true"
            ItemSelected="OnListViewItemSelected"
            ItemTapped="OnListViewItemTapped" x:Name="ImagePreviewListView"&gt;
                  &lt;ListView.ItemTemplate&gt;
                      &lt;DataTemplate&gt;
                          &lt;ViewCell&gt;
                              &lt;Grid Padding="10"&gt;
                                  &lt;Grid.Resources&gt;
                                      &lt;valueconverter:ByteArrayToImageSourceConverter x:Key="SourceConverter" /&gt;
                                  &lt;/Grid.Resources&gt;
                                  &lt;Grid.RowDefinitions&gt;
                                      &lt;RowDefinition Height="Auto" /&gt;
                                      &lt;RowDefinition Height="*" /&gt;
                                  &lt;/Grid.RowDefinitions&gt;
                                  &lt;Grid.ColumnDefinitions&gt;
                                      &lt;ColumnDefinition Width="Auto" /&gt;
                                      &lt;ColumnDefinition Width="*" /&gt;
                                  &lt;/Grid.ColumnDefinitions&gt;
                             &lt;Image Grid.RowSpan="2"
                             Source="{Binding ImageDocumentData, Converter={StaticResource SourceConverter}}"
                             Aspect="AspectFit"
                             HeightRequest="120"
                             WidthRequest="120" /&gt;
                                  &lt;Label Grid.Column="1"
                             Text="{Binding DocumentDescription}"
                             FontAttributes="Bold" /&gt;
                              &lt;/Grid&gt;
                          &lt;/ViewCell&gt;
                      &lt;/DataTemplate&gt;
                  &lt;/ListView.ItemTemplate&gt;
              &lt;/ListView&gt;
          &lt;/StackLayout&gt;
          &lt;StackLayout Grid.Row="1" Grid.ColumnSpan="3" Grid.Column="0" Orientation="Horizontal" HorizontalOptions="End" VerticalOptions="End"&gt;
              &lt;controls:ImageButtonControl
                  Clicked="btnRemove_Clicked"
                  FontSize="30"
                  Glyph="trash-alt"
                  HeightRequest="60"
                  HorizontalOptions="End"/&gt;
              &lt;controls:ImageButtonControl
                  Clicked="btnAdd_Clicked"
                  FontSize="30"
                  Glyph="plus"
                  HeightRequest="60"
                  HorizontalOptions="End"/&gt;
              &lt;controls:ImageButtonControl
                  Clicked="btnSave_Clicked"
                  FontSize="30"
                  Glyph="save"
                  HeightRequest="60"
                  HorizontalOptions="End"/&gt;
  
          &lt;/StackLayout&gt;
      &lt;/Grid&gt;
  &lt;/ui:PasAMBasePage&gt;
  </code></pre>
  
  <p>This is the code behind of the view:</p>
  
  <pre><code>    public partial class OrderItemImageDocumentationPage : PasAMBasePage&lt;OrderItemImageDocuViewModel&gt;
      {
          private IAppConfiguration _appConfig;
  
          public OrderItemImageDocumentationPage()
          {
              InitializeComponent();
          }
  
          public OrderItemImageDocumentationPage(OrderItemImageDocuViewModel viewModel, IEventLogService eventLog, ILifetimeScope scope,
              IUserInterfaceService uiService, IAppConfiguration appConfig)
              : base(viewModel, eventLog, scope, uiService)
          {
              InitializeComponent();
  
              _appConfig = appConfig;
  
              ViewModel.PropertyChanged += ViewModel_PropertyChanged;
          }
  
          private void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
          {
              if (e.PropertyName == nameof(OrderItemListViewModel.Order))
              {
                  //orderItemAppList.EventContext = ViewModel;
              }
          }
  
          private void OnListViewItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e)
          {
  
          }
  
          private void OnListViewItemSelected(object sender, Xamarin.Forms.SelectedItemChangedEventArgs e)
          {
  
          }
  
  
          private async void btnAdd_Clicked(object sender, EventArgs e)
          {
              RequestItemImageDocument document = new RequestItemImageDocument();
              document.RequestItemImageDocumentId = Guid.NewGuid();
              await CrossMedia.Current.Initialize();
              if (!CrossMedia.Current.IsCameraAvailable ||
      !CrossMedia.Current.IsTakePhotoSupported)
              {
                  await DisplayAlert("No Camera", "No camera available.", "OK");
                  return;
              }
              var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
              {
                  Directory = "AssetDocumentary",
                  SaveToAlbum = true,
                  CompressionQuality = 75,
                  CustomPhotoSize = 50,
                  PhotoSize = PhotoSize.MaxWidthHeight,
                  MaxWidthHeight = 2000,
                  DefaultCamera = CameraDevice.Front
              });
              if (!string.IsNullOrEmpty(file.Path)) 
              {
                  var result = await UserDialogs.Instance.PromptAsync("Fügen Sie eine optionale Textbeschreibung hinzu.", "Beschreibung");
                  document.DocumentDescription = result.Text;
                  byte[] data = null;
                  using (var stream = file.GetStream()) 
                  {
                      var fInfo = new System.IO.FileInfo(file.Path);
                      data = new byte[fInfo.Length];
                      stream.Read(data, 0, data.Length);
                  }
                  document.ImageDocumentData = data;
                  base.ViewModel.OrderItemImages.Add(document);
  
                  Android.Content.Context context = Android.App.Application.Context;
                  Android.Net.Uri filesUri = Android.Provider.MediaStore.Files.GetContentUri("external");
                  string where = Android.Provider.MediaStore.MediaColumns.Data + "=?";
                  //System.IO.File.Delete(file.Path);
                  context.ContentResolver.Delete(filesUri, where, new string[] { file.Path });
              }
  
          }
  
          private void btnSave_Clicked(object sender, EventArgs e)
          {
  
          }
  
          private void btnRemove_Clicked(object sender, EventArgs e)
          {
              if (ImagePreviewListView.SelectedItem != null) 
              {
                  var selectedItem = ImagePreviewListView.SelectedItem as RequestItemImageDocument;
                  var test = ViewModel.OrderItemImages.FirstOrDefault(
                      c =&gt; c.RequestItemImageDocumentId.Equals(((RequestItemImageDocument)ImagePreviewListView.SelectedItem)
                      .RequestItemImageDocumentId));
                  ImagePreviewListView.SelectedItem = null;
                  ViewModel.OrderItemImages.Remove(test);
              }
          }
      }
  </code></pre>
  
  <p>This is my converter:</p>
  
  <pre><code>    public class ByteArrayToImageSourceConverter : IValueConverter
      {
          public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
          {
              ImageSource xValue = null ;
              try 
              {
                  if (value != null) 
                  {
                      MemoryStream mem = new MemoryStream((byte[])value);
                      xValue = ImageSource.FromStream(new Func&lt;Stream&gt;(() =&gt; { return mem; }));
                  }
  
              }catch(Exception ex) 
              {
  
              }
              return xValue;
          }
  
          public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
          {
              throw new NotSupportedException();
          }
      }
  </code></pre>
  
  <p>This is the view model:</p>
  
  <pre><code>    public class OrderItemImageDocuViewModel : ApplicationDataBaseViewModel, INavigationEventHandler
      {
          #region Klassenvariablen
  
          private readonly int _pagingSize = 20;
          private IAppConfiguration _appConfig;
          private ILifetimeScope _scope;
          private IBarcodeParserService _barcodeParser;
          private IEventLogService _eventLog;
          private IUserDataService _userData;
          private int _itemsToLoadCount;
          private ObservableCollection&lt;RequestItemImageDocument&gt; _orderItemImages = new ObservableCollection&lt;RequestItemImageDocument&gt;();
          private OrderItem _orderItemContext = null;
          #endregion Klassenvariablen
  
          #region Konstruktor
  
          public OrderItemImageDocuViewModel(ILifetimeScope scope, IDataRepositoryService dataRepository, IBarcodeParserService barcodeParserService, IEventLogService eventLog, IUserDataService userData, ITranslationService translationService, IAppConfiguration appConfig)
              : base(dataRepository)
          {
              _eventLog = eventLog.Initialize(typeof(OrderItemImageDocuViewModel));
              _scope = scope;
              _appConfig = appConfig;
              _userData = userData;
              _barcodeParser = barcodeParserService;
              TranslationService = translationService;
  
              _itemsToLoadCount = _pagingSize;
  
  
          }
  
          #endregion Konstruktor
  
          #region Properties
  
          [NavigationParameter]
          public Order Order { get; set; }
  
          public IEventLogService EventLog =&gt; _eventLog;
  
          public bool IsLoading { get; set; }
  
          public bool DatabasesMissing { get; set; }
  
  
  
          public ITranslationService TranslationService { get; set; }
  
          public IList&lt;OrderItem&gt; OrderItems { get; set; }
  
          public IOrderTypeScanHandling ScanHandler { get; set; }
  
          public ObservableCollection&lt;RequestItemImageDocument&gt; OrderItemImages 
          {
              get 
              {
  
                  return _orderItemImages;
              }
              set 
              {
                  _orderItemImages = value;
                  base.OnPropertyChanged("OrderItemImages");
              }
          }
          #endregion Properties
  
          #region Functions
  
          #endregion
  
          public override async void OnNavigationParametersProvided(NavigationContext context)
          {
              if (!DatabasesMissing)
              {
                  IsLoading = true;
  
                  try
                  {
                      //await InitializeData();
  
                      //await LoadDataOnDemand();
                  }
                  catch (Exception ex)
                  {
                      //ex.TrackError();
                  }
  
                  IsLoading = false;
              }
          }
  
      }
  </code></pre>
  
  <p><strong>[Update]</strong>
  I have extracted the specific code and put it into a standalone solutions.
  That solution can be found at <a href="https://github.com/Q-Tec90/ImageListTest" rel="nofollow noreferrer">https://github.com/Q-Tec90/ImageListTest</a><br>
  In order to reproduce the issue just add 3 images to the listview. Afterwards select the second entry in the listview and click on the remove button. You will get the runtime exception.<br>
  I am running it against an android 6 device. The device or emulator needs to have a front camera in order to make the images.</p>