在更新绑定到 Listview 的 ObservableCollection 中的项目时,指定的转换无效

Specified cast not Valid when updating Item in ObservableCollection bound to Listview

我正在尝试使用 https://github.com/jamesmontemagno/MediaPlugin 在 Xamarin 中将图像从设备添加到我的应用程序。奇怪的是,添加 Item 在某些时候引发了异常 "between the lines"。我不知道如何调试它并假设它恰好实施 OnPropertyChanged 错误。

我将异常包装在 Try/Catch 块中,令我惊讶的是该项目实际上已被添加并且 App.api.message.MediaFiles.Count() 增加了。这让我假设 Exeption 实际上发生在 .Add(Item) 之后,但不是在 .Add(Item)

这必须是 OnPropertyChanged()(但为什么调试器不向我显示那部分代码?)或者 Xamarin 将 Listview 绑定到 ...Thumbnail 的幕后魔法。

然而,由于这两个选项对我来说都是相对较新的,所以这里很可能会出现错误或误解,如能提供有关如何或在何处调查此问题的任何提示,我们将不胜感激。

以下是我的详细操作:

 [...]
    public MainPage()
    {
        InitializeComponent();
        BindingContext = App.api.message;
        Media.ItemsSource = App.api.message.MediaFiles;
      [...]
    }

XAML 中的列表视图:

[...]
<ListView x:Name="Media" BackgroundColor="#f1f1f1" HasUnevenRows="true" IsVisible="true" Header="Media" ItemTapped="RemoveImage" RowHeight="90" HeightRequest="120">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Image Source="{Binding thumbnail}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView> 
[...]

由于 file 来自采摘或拍摄图像,我这样做:

    public void AddFile(MediaFile file)
    { 
        Classes.MessageClass.Media Item = new Classes.MessageClass.Media();

        Item.Filename = file.Path;

        Item.Thumbnail = ImageSource.FromStream(() =>
        {
            var stream = file.GetStreamWithImageRotatedForExternalStorage();
            return stream;
        });

        file.Dispose();

        FileInfo fileInfo = new FileInfo(Item.Filename);
        Item.Size = fileInfo.Length;

        Console.WriteLine("\n\nOriginal File:{0} \n{1:###,###,###} Bytes\nCaption: {2}\nContent Type: {3}", Item.Filename, Item.Size, Item.Caption,Item.ContentType);

        try
        {
            App.api.message.MediaFiles.Add(Item);  //EXEPTION "Specified cast not Valid"
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exeption: " + ex.Message + " " + ex.Data.Values.ToString());
        }
        Console.WriteLine("Attached Images: " + App.api.message.MediaFiles.Count());
        App.api.message.HasMedia = true;

        UpdateImagesUI();
    }

最后是我对 Classes.MessageClass.Media 的定义。 (我添加了值以排除空值问题):

public class Media
    {
        public string Caption { get; set; } = "";
        public string Filename { get; set; } = "";
        ImageSource thumbnail;
        public long Size { get; set; } = 0;
        public string ContentType { get; set; } = "";
        public bool IsVideo { get; set; } = false;
        public ImageSource Thumbnail
        {
            get
            { 
                return thumbnail;
            }
            set 
            { 
                if ((thumbnail != value) && (value != null))
                {
                    thumbnail = value;
                    Console.WriteLine("Image Updated");
                    OnPropertyChanged("Thumbnail");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var changed = PropertyChanged;
            if (changed != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

in MessageClass()MediaFiles = new ObservableCollection<Media>();

最后堆栈:

 (System.Collections.Specialized.NotifyCollectionChangedEventArgs e) [0x0000f] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/mcs/class/referencesource/System/compmod/system/collections/objectmodel/observablecollection.cs:288 
 at  System.Collections.ObjectModel.ObservableCollection`1[T].OnCollectionChanged (System.Collections.Specialized.NotifyCollectionChangedAction action, System.Object item, System.Int32 index) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/mcs/class/referencesource/System/compmod/system/collections/objectmodel/observablecollection.cs:351 
 at System.Collections.ObjectModel.ObservableCollection`1[T].InsertItem (System.Int32 index, T item) [0x00024] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/mcs/class/referencesource/System/compmod/system/collections/objectmodel/observablecollection.cs:219 
 at System.Collections.ObjectModel.Collection`1[T].Add (T item) [0x00020] in /Library/Frameworks/Xamarin.iOS.framework/Versions/12.0.0.15/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/collections/objectmodel/collection.cs:67 
 at SegelnBlogsEditor.MainPage.AddFile (Plugin.Media.Abstractions.MediaFile file) [0x0009e] in /Users/hinnerkweiler/wwwroot/SegelnBlogsEditor/SegelnBlogsEditor/MainPage.xaml.cs:292

ImageSource.FromStream 方法将一个 Action 作为参数,每次需要渲染 ViewCell 时都会对其求值。在操作中使用 file 引用供以后使用并处理它会导致异常。

编辑:

更好的方法是从文件名中获取图像

Image.Thumbnail = ImageSource.FromFile(Item.Filename);