Search code examples
c#androidioshandlermaui

MAUI Handler Xaml to Platform Connection


I am using the handler feature of MAUI, but the methods in the platform specific classes are not being called.

This is the click event for the xaml page:

private void ActivateCamera(object sender, EventArgs e)
{
    cameraView.MakePhoto();
}

This are the Interface and the View classes:

public interface ICameraView : IView
{
    void MakePhoto();
}

public class CameraView : View, ICameraView
{
    CameraViewHandler StrongHandler => Handler as CameraViewHandler;

    public void MakePhoto() => StrongHandler?.Invoke(nameof(MakePhoto), null);
}

This is the Handler:

public class CameraViewHandler : ViewHandler<ICameraView, NativePlatformCameraPreviewView>
{

    public static CommandMapper<ICameraView, CameraViewHandler> CameraCommandMapper = new()
    {
        [nameof(ICameraView.MakePhoto)] = MapMakePhoto
    };

    public static void MapMakePhoto(CameraViewHandler handler, ICameraView cameraView, object? parameter) 
        => handler.TakePhoto();

    public void TakePhoto() => _cameraController?.TakePicture();
     // The TakePicture method is implemented in the iOS and android files, but as said, is not being executed
}

I have this in MauiProgramm:

handlers.AddHandler(typeof(CameraView), typeof(CameraViewHandler));

Can someone see why this is not working?


Solution

  • Did you check the official document about creating a custom control using handlers? The mapped method should in the platform custom handler class.

    So CameraViewHandler.cs should be such as:

    public partial class CameraViewHandler : ViewHandler<ICameraView, NativePlatformCameraPreviewView>
    {
    
        public static CommandMapper<ICameraView, CameraViewHandler> CameraCommandMapper = new()
        {
            [nameof(ICameraView.MakePhoto)] = MapMakePhoto
        };
    }
    

    And the MapMakePhoto method in the CameraViewHandler.Android.cs:

     public static void MapMakePhoto(CameraViewHandler handler, ICameraView cameraView)
    {
        handler.PlatformView?.NativeMethod();
    }
    

    For more information, you can refer to the official sample on the github about the handlers.

    Update

    Don't forget the construction method of the handler:

    public CameraViewHandler() : base(CameraViewMapper, CameraCommandMapper) { }