call native method from PCL failing Xamarin.From > 4

parzivalmxparzivalmx Member ✭✭

When trying to call a native method from my Shared Project (.NET Standard 2.0) to my iOS project. It not entering the CallToNativeMethod on my iOS project when using Xamarin.Forms version 4 or up. I followed this structure:

Shared Project

//Namespace 
//YourClass
public event EventHandler CallToNativeMethod;

public void RaiseCallToNativeMethod()
{
    if (CallToNativeMethod != null)
        CallToNativeMethod(this, new EventArgs());
    // C# 6 way (Does the same thing as the line above, but looks cleaner)
    // CallToNativeMethod?.Invoke(this, new EventArgs());
}

iOS / Android /etc. Renderer

//Namespace
//ClassOfRenderer
//Inside your OnElementChanged Method
((YourClass)Element).CallToNativeMethod += (sender, e) =>
{
    Control.YourNativeMethodIsCalledHere();
}

Back in Shared Project

var yourClass = new YourClass();
yourClass.RaiseCallToNativeMethod();

But the issue is that is not firing this part on the iOS Rendered:

  ((YourClass)Element).CallToNativeMethod += (sender, e) =>
    {
        Control.YourNativeMethodIsCalledHere();
    }

Do i need to do something different? Its working on Xamarin.Forms 3.6.0.539721

Best Answer

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    Where did you place the event registration code? I consumed it in the OnElementChanged and it works fine on my side:

    protected override void OnElementChanged(VisualElementChangedEventArgs e)
    {
        base.OnElementChanged(e);
    
        if (e.NewElement != null)
        {
            ((MainPage)Element).CallToNativeMethod += (sender, args) =>
            {
                Debug.WriteLine("event fires");
            };
        }
    }
    

    My Forms version is 4.0.0.425677. Test my attachment to see the effect.

  • parzivalmxparzivalmx Member ✭✭

    Yes, it's been consumed in the OnElementChanged. I got nothing on the output for the Debug.WriteLine

     protected override void OnElementChanged(VisualElementChangedEventArgs e)
     {
           base.OnElementChanged(e);
    
           if (e.NewElement != null)
           {
                ((MainPage)Element).CallToNativeMethod += (sender, args) =>
                {
                      Debug.WriteLine("event fires");
                 };
             }
       }
    
  • parzivalmxparzivalmx Member ✭✭

    Still not working, if I downgrade to Xamarin.Forms 3.6.0.539721 I can see the "Event fires" log on my output.

  • parzivalmxparzivalmx Member ✭✭

    Yes it works on your Sample, but on my case I figured it is behaving different because I'm using it on a Tabbed Page. I was able to fix that but still I'm not getting the same behavior as Xamarin 3.

    Issue is on this thread

    https://forums.xamarin.com/discussion/161517/awakefromnib-not-being-called-on-onelementchanged#latest

Sign In or Register to comment.