CommunityToolkit / Maui

The .NET MAUI Community Toolkit is a community-created library that contains .NET MAUI Extensions, Advanced UI/UX Controls, and Behaviors to help make your life as a .NET MAUI developer easier
https://learn.microsoft.com/dotnet/communitytoolkit/maui
MIT License
2.2k stars 379 forks source link

[BUG] Cannot capture image with CameraView using just MVVM #1993

Open jfversluis opened 2 months ago

jfversluis commented 2 months ago

Is there an existing issue for this?

Did you read the "Reporting a bug" section on Contributing file?

Current Behavior

As outlined in our docs we can use the CaptureImageCommand to capture an image while using the MVVM pattern in our .NET MAUI app.

However, to access the actual media that was captured we need to subscribe to the MediaCaptured event. And by having to use an event suddenly I am breaking the MVVM pattern.

Expected Behavior

We need to have a way of also capturing the media in an MVVM fashion to not force people into bad patterns.

Steps To Reproduce

N/A

Link to public reproduction project repository

https://github.com/CommunityToolkit/Maui

Environment

- .NET MAUI CommunityToolkit Camera: 1.0.2
- OS: N/A
- .NET MAUI: 8.0.61

Anything else?

Additionally I think we may want to consider giving the CaptureImageCommand a default value for the CancellationToken or have an override without it. This makes consuming in XAML a bit harder.

polincev commented 2 months ago

For anybody stumbling upon this issue, a functional work-around I'm currently using is the EventToCommandBehavior from the Community Toolkit. This doesn't require any code-behind and propagates the captured media to the ViewModel.

Here is a sample XAML that maps the MediaCaptured event to a command named MediaCapturedCommand:

<toolkit:CameraView.Behaviors>
    <toolkit:EventToCommandBehavior
        EventName="MediaCaptured"
        x:TypeArguments="toolkit:MediaCapturedEventArgs"
        Command="{Binding BindingContext.MediaCapturedCommand, Source={x:Reference Camera}}"/>
</toolkit:CameraView.Behaviors>

The Command needs to accept a parameter of type MediaCapturedEventArgs in this case.

EDIT

Just to avoid any confusion, the "Camera" which is referenced in the Binding Source is the name I have assigned to the ContentPage (x:Name="Camera")