0

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.

Peter
  • 11,260
  • 14
  • 78
  • 155
  • Can you show real code not pseudo code? Not sure why you are doing "pinchgr += OnViewPinched; pangr += OnViewPanned;" and "pinchgr -= OnViewPinched; pangr -= OnViewPanned;" – jgoldberger - MSFT Jan 20 '17 at 00:51
  • Can you calling `enableGestures` within an enumerated `View` loop? i.e. http://stackoverflow.com/a/605390/4984832 Without the full context of how you are doing this, any answers are just guessing, but the bottom line is enumerating and modifying the same collection is *generally* not allowed. – SushiHangover Jan 20 '17 at 00:54

1 Answers1

1

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.

Stephane Delcroix
  • 16,134
  • 5
  • 57
  • 85
  • Thank you all for your help. Although I was not doing any enumeration, I think you were on the right track. Xamarin must be enumerating all the recognizers while I was adding the new recognizer. Hence the problem. – Peter Jan 21 '17 at 21:33