Ever wanted to have an Icon element attached to a Xamarin.Forms.Button control? Welcome to another lightening short post of me hacking around Xamarin.Forms elements!
No custom renderers, no platform specific code and no third party libraries! Just by using pure out of the box Xamarin.Forms! 😉
That’s what we gonna be build yol!
Now for something like that you’re going to assume we need some custom renderers or platform specific code or third party library use, but no no no! not on my watch! 😀
In this recipe we’re going to use the same concept that we used in the XFHACKS-001 article, stacking Elements on top of each other using Xamarin.Forms Grid Layout. So here we’re placing an Image on top of a Button.
Now you might wonder wouldn’t that void the touch event of the Button, since the Image will be covering a part of the Button touch area? Now that’s where the magic property called InputTransparent comes into play. Using this property we can disable the touch input interaction for any given View and pass it down to the next child underneath. 😀
Behold the golden XAML code!
There you have it just like we discussed, inside the Grid we have a Button, and on top of that we have an Image, with our magical property InputTransparent set to true, which disables the touch events of the Image redirecting them on to the Button itself. So by this the whole Image and Button works as a single Button control.
I have given a little padding to the Image, so that the icon doesn’t corner itself in the Button. The Image has a fixed width and height of 25 units, and its set to the second column of the Grid, whereas the Button spreads across two columns filling up the entire space of the Grid. Thereby you can set any fixed size to the Grid itself or let it Fill up whatever the parent container its holding.
There you have it running on Android, iOS and UWP like a charm!
Grab it on Github!
Well then, that’s it for now. More awesome stuff on the way!
Cheers! 😀 share the love!