Xamarin.Forms and Draggable View. The New Year Tale

It’s New Year Tale about how to make Draggable View in Xamarin.Forms Application.

đŸ‡ș🇩 Bohdan Benetskyi
Nerd For Tech

--

Once upon a time, a new requirement arrived in Fairy-tale land. “We need to create Draggable Button inside inner area of some control”, — it says. “That’s not a big deal”, — thought one of the developers, but he did not know that the Dark Lord of Mordor was not asleep.

“I want to make it reusable across different projects and scenarios” — he said — “That’s why it should allow putting any View inside!”

In the end, implementation requirements to the new Draggable View were next:

  • Create new Custom Control inherited from ContentView to give a possibility to put any content.
  • Drag restriction by some Limit Area(his parent)

And the work began


The Old Good Custom Control

As usually implementation starts with well known four words: public class DraggableView : ContentView {} . But what Bindable Properties do we need to define? We already can set any Content thanks to ContentView . LimitArea —we need to limit the translation of our control inside parental control! For that, we need a new model — DraggableArea Model.

Two Towers - Android and iOS platform renderers

The well-known base of Custom Renderer was done and the developer start thinking about how to limit its translation by parent view.

“We need to handle a long click to start dragging control” — said Developer.

“We don’t have properties were to set new temporary position” — said a developer.

The Land of Shadow — logic to drag custom control

Returning back to DraggableView the developer wasn’t sure if we needed to create new properties like Bindable. After long hours of meditation with beer, a solution comes into his mind — “This should be Bindable Properties because allow developers to bind and modify them without modification of Custom Renderer.”

After that, we need to identify Moving Gesture to set correct NewX and NewY before Translating Control itself.

“There is only a translation of element left” — the developer thought.

The developer was happy with all work done and started testing his control with a button inside


Over the city of Gondor doubt and great dread had hung — Button Command doesn’t work well on both platforms.

Fear and doubt were in the developer’s mind, but a solution was obvious. After clarifying requirements, he knows that inside may be only one clickable element, never more.
“In that case” — he shouted — “We can add Command Bindable Property into our DraggableView and use only when placed Content inside it has to respond when user clicks on it.”

All things now went well, with hope always of becoming still better


It is the happy end of our New Year Tale. Special thanks to Andrii Kharechko.

Below you can find all code together for XF & Android & iOS 😉

--

--