Xamarin.Forms and Draggable View. The New Year Tale
Itâs New Year Tale about how to make Draggable View in Xamarin.Forms Application.
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 đ