Peter
Peter

Reputation: 11890

Xamarin view - Error on re-adding gesture recognizer

In my Xamarin app, based on a state, I need to add or remove pan/pinch gesture recognizers to Xamarin Forms view. Here is some pseudo-code:

public void enableGestures(Xamarin.Forms.View v, bool isEnable) {

   if (isEnable) {
      pinchgr += OnViewPinched;
      pangr += OnViewPanned;
      v.GestureRecognizers.Add(pinchgr);
      v.GestureRecognizers.Add(pangr);
   }else {
      pinchgr -= OnViewPinched;
      pangr -= OnViewPanned;
      v.GestureRecognizers.Remove(pinchgr);
      v.GestureRecognizers.Remove(pangr);
   }
}

The very first time, adding gesture recognizers work fine. Even removing them later works fine. However, when I try to add them once again, I get an invalid operation exception "Collection was modified; enumeration operation may not execute."

Wondering if anyone knows how to overcome this problem. Regards.

Upvotes: 0

Views: 119

Answers (1)

Stephane Delcroix
Stephane Delcroix

Reputation: 16232

It looks like you're modifying an enumerable collection from within a loop.

Instead of looping through the IEnumerable, loop through a .ToList() or .ToArray() version of it.

Upvotes: 1

Related Questions