Prozedsq
Prozedsq

Reputation: 67

Xamarin Forms - Send event to native and retrieve value

I'm currently making a custom view to preview camera of the device, and trying to trigger a "take picture" event.

Right now, i can trigger the event, but i don't find a solution to return the picture to Xamarin Forms Shared Code.

Here's what i'm doing from the Xamarin Forms custom control :

public class CameraPreview : View
{
    public event EventHandler TakePictureRequested;

    public void TakePicture()
    {
        TakePictureRequested?.Invoke(this, EventArgs.Empty);
    }
}

And here from Native code for Android for example :

protected override void OnElementChanged(ElementChangedEventArgs<CameraPreview> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement != null)
        {
            e.OldElement.TakePictureRequested += OnTakePictureRequested;
        }
        if (e.NewElement != null)
        {
            if (Control == null)
            {
                cameraPreview = new CameraPreviewView(Context);
                SetNativeControl(cameraPreview);
            }
            Control.Preview = Camera.Open(getBackCameraId());

            e.NewElement.TakePictureRequested += OnTakePictureRequested;
        }
    }

    void OnTakePictureRequested(object sender, EventArgs e)
    {
        cameraPreview.TakePicture();
    }

The idea is that "OnTakePictureRequested" from Native Code can return the value to the Xamarin Forms.

Anyone has an idea ? Thanks

Upvotes: 1

Views: 602

Answers (2)

Morse
Morse

Reputation: 9144

In your native view access Xamarin Forms view by

var xamarinFormsView = e.NewElement as CameraPreview;
xamarinFormsView .DoSomethingAfterPictureTaken("blahblah");

and in CameraPreview add a method to access and do something with the value you want to send over

void DoSomethingAfterPictureTaken(string valueFromNative){
//access valuefromNative as you wish
}

Upvotes: 1

Leo Zhu
Leo Zhu

Reputation: 15031

maybe you could try to use MessagingCenter to pass the value

Xamarin.Forms MessagingCenter enables view models and other components to communicate without having to know anything about each other besides a simple Message contract.It is a static class with Subscribe and Send methods that are used throughout the solution.

you just need Subscribe it in your CameraPreview

then Send the value from your CustomRenderer.

you could refer to MessagingCenter

Upvotes: 0

Related Questions