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

时间:2018-10-13 17:37:14

标签: c# xamarin xamarin.forms plugin.media.crossmedia

我正在尝试使用https://github.com/jamesmontemagno/MediaPlugin将设备中的图像添加到Xamarin中的App中。奇怪的是,添加“物品”会在“两线之间”的某个点引起豁免。我不知道如何调试它,并假设发生OnPropertyChanged错误。

我将试品包装在Try / Catch块中,令我惊讶的是,实际上已添加了商品,而App.api.message.MediaFiles.Count()已增加。这使我假设Exeption实际上是在.Add(Item)之后而不是在之后发生。

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

但是,由于这两种选择对我来说都是相对较新的,因此在这里很可能会犯错误或误解,并且希望获得关于如何或在何处进行调查的任何提示。

这是我详细做的事情:

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

XAML中的Listview:

[...]
<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

1 个答案:

答案 0 :(得分:0)

ImageSource.FromStream方法将Action作为参数,每次需要呈现ViewCell时都会对其进行评估。在操作内部使用file引用供以后使用并处置它会导致异常。

编辑:

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

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