Xamarin.Forms: Image Button Recipe

Today, we will learn how to create an Image Button in Xamarin Forms. Most of you will think, why? Isn't there an Image property of Buttons? Yes, there is an Image property in Button but that doesn't meet the needs completely since it adds the image as an icon to the text in the button. So to solve this problem, I came up with this tweak.

Ingredients:

Procedure:

1. To create a new application in Visual Studio we will select New Project from the Welcome screen.

2. Select Mobile Apps from the installed templates of Visual Studio under C#. Now as you can see we have two options for a Blank App, one is Xamarin.Forms Portable and Xamarin.Forms Shared. We will be working on Xamarin.Forms Portable.


3. Now you can see that the solution file contains the 4 projects XamarinSample (Portable), XamarinSample.Android, XamarinSample.iOS and XamarinSample.WinPhone. We will now right-click on the first project, XamarinSample (Portable) and click on Add -> New Item from the context menu.


4. Now we will select Forms XAML Page from the dialog and name it.


5. Once the Forms XAML Page is added to the project, open the App.Cs and write the following code in the constructor:
  1. MainPage = new NavigationPage(new MainPage());  

The App.cs will look like this:

6. Now go back to the Forms XAML Page we created in Step 4, in other words the MainPage that we called in the constructor. And replace the Label tags with:

  1. <Image x:Name="img" Source="image.jpg" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"></Image>  

The MainPage.xaml will now look like this:

 

7. Now we will write the Tap Gesture Recognizers code in MainPage.xaml.cs as in the following:

 

  1. //Creating TapGestureRecognizers  
  2. var tapImage = new TapGestureRecognizer();  
  3. //Binding events  
  4. tapImage.Tapped += tapImage_Tapped;  
  5. //Associating tap events to the image buttons  
  6. img.GestureRecognizers.Add(tapImage);  
  7. void tapImage_Tapped(object sender, EventArgs e)  
  8. {  
  9.   // handle the tap  
  10.   DisplayAlert("Alert""This is an image button""OK");  
  11. }  

 The MainPage.xaml.cs will now look like this:

 
8. Now add the "image.jpg" in the all the three projects of the various OSs in the following way:

Android: Add the file in ImageButtonRecipe.Droid -> Resources -> drawable folder.

iOS: Add the file in ImageButtonRecipe.iOS -> Resources.

WinPhone: Add the file in ImageButtonRecipe.WinPhone.

9. Now the Image Button will look like this across all the devices:

 

10. On clicking these buttons it will display a pop-up message.

 
 This is the simplest way to have an image button in your Xamarin.Forms app across all your devices. 
 
Make some beautiful apps using Xamarin.Forms and tweet your queries to @adiiaditya.

Up Next
    Ebook Download
    View all
    Learn
    View all