I have added the class
public class ObservableCollectionEx<T> : ObservableCollection<T>
{
public bool SuppressEvents { get; set; } = true;
public ObservableCollectionEx(): base() {}
public ObservableCollectionEx(IEnumerable<T> collection): base(collection){}
public ObservableCollectionEx(List<T> list): base(list){}
public void RaiseCollectionChangedEvent()
{
SuppressEvents = false;
this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (!SuppressEvents)
base.OnCollectionChanged(e);
}
}
ViewModel
public ObservableCollectionEx<MyModel> myCollection = new ObservableCollectionEx<MyModel>();
Method1()
{
myCollection.SuppressEvents = true;
//some changes in Obs Collection.
// some add/remove/insert operations on collection
myCollection.RaiseCollectionChangedEvent(); // works
}
Method2()
{
myCollection.SuppressEvents = true;
//some changes in Obs Collection.
// some add/remove/insert operations on collection
myCollection.RaiseCollectionChangedEvent(); // breaks
}
And in ViewModel, I'm suppressing the events by toggling the variable before the changes and after changes by calling the RaiseCollectionChangedEvent
method. It is working in some scenarios. In some, it is throwing a null pointer exception. I'm not able to observe what causes the exception.
P.S. Error
Message
Object reference not set to instance of an object
StackTrace
Android:
at Xamarin.Forms.Platform.Android.GridLayoutSpanSizeLookup.GetSpanSize (System.Int32 position) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\GridLayoutSpanSizeLookup.cs:18 at AndroidX.RecyclerView.Widget.GridLayoutManager+SpanSizeLookup.n_GetSpanSize_I (System.IntPtr jnienv, System.IntPtr native__this, System.Int32 position) [0x00008] in D:\a\1\s\generated\androidx.recyclerview.recyclerview\obj\Release\monoandroid9.0\generated\src\AndroidX.RecyclerView.Widget.GridLayoutManager.cs:510
iOS:
at Xamarin.Forms.Platform.iOS.ItemsViewController
1[TItemsView].UpdateTemplatedCell (Xamarin.Forms.Platform.iOS.TemplatedCell cell, Foundation.NSIndexPath indexPath) [0x00031] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewController.cs:278 at Xamarin.Forms.Platform.iOS.ItemsViewController1[TItemsView].CreateMeasurementCell (Foundation.NSIndexPath indexPath) [0x0007b] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewController.cs:619