Search code examples
c#xamarin.formscustom-renderer

How to access method from view inside a Xamarin Forms custom renderer?


I have the following code:

public partial class PhrasesFrameRendererClass : Frame
{
    .....
    void getRandomWords() {
       // more code here that involves getting random numbers 
       // and updating a grid's bindingcontext
    }
}

In my custom renderer I want to be able to call the getRandomWords on swipe left gesture like below:

public class PhraseFrameCustomRenderer : FrameRenderer
{
   UISwipeGestureRecognizer leftSwipeGestureRecognizer;
   protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
   {
       base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
          // Call getRandomWords() here
       });
   }
}

Is this possible? Any ideas on how this could be done?


Solution

  •  base.OnElementChanged(e);
       leftSwipeGestureRecognizer = new UISwipeGestureRecognizer();
       leftSwipeGestureRecognizer.Direction = UISwipeGestureRecognizerDirection.Left;
       leftSwipeGestureRecognizer.NumberOfTouchesRequired = 1;
       leftSwipeGestureRecognizer.AddTarget((obj) =>
       {
          // Call getRandomWords() here
          var frame = Element as PhrasesFrameRendererClass ;
          if(frame!=null){
               frame.getRandomWords();
          }
       });