1
votes

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

2
Take a look at TaskCompletionSource. Its pretty straight forward, if you still need help we can take a look at what you've tried - shanranm
Hello @shanranm , I already tried it, but it seems i can't return something from an Invoke - Prozedsq
You need to await the Task returned by TaskCompletionSource - shanranm
Yes but it can't work for an Event Handler. Invoke is a void function and cannot be awaited. What i want, is retrieving the information in my Custom control. - Prozedsq
what value you want to return? - Morse

2 Answers

1
votes

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
}
0
votes

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