将MediaPicker图像添加到ListView会导致System.ObjectDisposedException.&



我有一个表格填写的数据,包括一个图像,然后进入一个列表视图。当我点击一个按钮,得到一个图像,它的工作原理,它进入表单,但是,当我点击另一个按钮,将其添加到列表视图,错误[系统。ObjectDisposedException: '无法访问已处置的对象。'对象名称:'流已关闭']出现。

谢谢你的帮助

当我按下添加图像按钮时:

var ActionPhoto = await DisplayActionSheet("Ajouter une pièce-jointe depuis:", "Annuler", null, "Galerie", "Caméra");
switch (ActionPhoto)
{
case "Galerie":
var Galerie = await MediaPicker.PickPhotoAsync(new MediaPickerOptions { Title = "Choisir une image" });
if (Galerie != null)
{
var voirImageGalerie = await Galerie.OpenReadAsync();
Image_Photos.Source = ImageSource.FromStream(() => voirImageGalerie);
}
break;

case "Caméra":
var camera = await MediaPicker.CapturePhotoAsync();
if (camera != null)
{
var voirImageCamera = await camera.OpenReadAsync();
Image_Photos.Source = ImageSource.FromStream(() => voirImageCamera); 
}
break;
}

当我按下listView的add按钮时:

App.listePosteNoteFrais.Add(new Data{PostePJ = Image_Photos.Source});

In my Data Class:

public ImageSource PostePJ { get; set; }

添加到listview的内容:

<Image x:Name="Image_PostePJ" Source="{Binding PostePJ}" HeightRequest="150" WidthRequest="150" Grid.Row="0" Grid.Column="12"/>

给定代码:

ImageSource.FromStream(() => voirImageCamera)

FromStream的参数:

() => voirImageCamera

在每次需要映像时执行。

异常消息:

系统。ObjectDisposedException: '无法访问已处置的对象。'对象名称:'流已关闭。

告诉您流(voirImageCamera)不再可用。

我不确定是什么内部代码在处理这个流。也许MediaPicker认为它不再需要了。或者可能是由于从一个图像源复制到另一个。或者关于ListView如何/何时访问图像源。

如Xamarin文档所示。要点:媒体选择器/一般用法,使用MediaPicker的OpenReadAsync结果的安全方法是将流保存在本地文件中,然后使用该文件作为图像源:

// save the file into local storage
var newFile = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
using (var stream = await photo.OpenReadAsync())
using (var newStream = File.OpenWrite(newFile))
await stream.CopyToAsync(newStream);

然后将图像源设置为该文件:

Image_Photos.Source = ImageSource.FromFile(newFile);

FromFile的优点是它应该能够在任何需要的时候打开文件-没有stream保持打开状态。

注意:文档示例使用CacheDirectory。根据具体情况,FileSystem.AppDataDirectory可能更合适(应该无限期保存的文件)。

相关内容

最新更新