Home is where the [.net] compiler is.

Turning Events into Commands

Have you ever used some control in Xamarin.Forms that appears to have an event instead of a command? You are working the MVVM love and then you come across that annoying control. Almost all the Xamarin.Forms controls have both events and commands, enabling choice, but you do get those non-conforming ones…

I was lurking on the Xamarin forums and I came across a question regarding the event-only design of the SkiaSharp SKCanvasView. The SKCanvasView has a PaintSurface event that allows you to draw on the view with SkiaSharp commands.

There is nothing wrong with the event as it stands, but things get messy when all the data is in a view model. In simple cases, this is easy to resolve. Take a small example where there is only one view model, which is the binding context for an entire Page:

This will work as everything is pretty much straight-forward. However, what happens if the canvas is in a ListView or if there are several canvases on the page? We would end up with a messy code-behind and probably a few memory leaks.

That’s it! Our canvas is now command-based and can be drawn on from the view model.

This is just a very limited behavior, for one specific event for one specific view. But, behaviors are very powerful and can be used to do many more things. One such use is to make a more generic behavior that can map any event to any command: