Tag Archives: Xamarin Forms

Creating Custom “Clicked” Event Handlers in Xamarin.Forms

Something I needed to do in a recent Xamarin.Forms project was to create a subclass of Image that had a custom ‘Clicked’ event handler attached. In other words, I simply wanted to be able to set Clicked=”MyHandler” in the XAML description of the image and have MyMethod called when the image was clicked – much the same as the Xamarin.Forms.Button class currently works.

Whilst I was used to catching touch events using TapGestureRecognizer, the syntax for setting up a custom event handler that could be set from XAML eluded me for quite some time and, as it was tough to find any decent examples online, I decided to create my own.

So here’s a simple ClickableImage subclass of Image with a custom Clicked handler added. The code is extremely straightforward so you could very easily copy and paste to create a similar ClickableLabel subclass of Label, or a custom ContentView, or whatever…

using System;
using Xamarin.Forms;

namespace Com.Bitbull.Examples
    public class ClickableImage:Image
        // This is the event handler that will be set from your XAML
        public event EventHandler Clicked;

        public ClickableImage()
            // Set up a gesture recognizer to respond to touch events
            TapGestureRecognizer tap = new TapGestureRecognizer();
            tap.Command = new Command(OnClicked);

        // Called every time the image is clicked
        public void OnClicked(object sender)
            if (Clicked != null)
                // Call the custom event handler (assuming one has been set)
                // You could always subclass EventArgs to send something more useful than
                // EventArgs.Empty here but more often than not that's not necessary
                this.Clicked(this, EventArgs.Empty);

These articles can take a lot of time and effort to put together. If you found this useful and would like to help me create more content like this like you can support me below – I really appreciate it!

Buy Me a Coffee at ko-fi.com

Creating Bindable Properties in Xamarin.Forms v3.0+

This is an updated version of what has proven to be one of the most popular posts on this site – a simple ‘cut and paste’ solution to create custom bindable properties in Xamarin.Forms. The original post can be found here.

Unlike many other online examples, this one allows you to set the property both programmatically and via XAML. I’ve updated the code to make it more ‘cut,paste,search,replace’ friendly and to get rid of the generic types which will be deprecated in future versions of Xamarin.Forms.

A lambda expression is used to route the PropertyChanged call back to the originating object – generally I’ve found this approach more useful than a static callback. Please excuse the gratuitous casting!

To use simply replace MyClass with the name of your containing class (which will be a subclass of BindableObject), FooBar with the name of your property, and the references to bool to the type of your property.

Hopefully the inline comments make the code self-explanatory. If you run into any problems or just find this useful please leave a comment!

#region foobarproperty
// Creates the bindable property using a lambda expression to route the PropertyChanged 
// handler back to the containing class
public static readonly BindableProperty FooBarProperty = BindableProperty.Create(   
    nameof(FooBar), 	// The name of the property you are creating
    typeof(bool), 	// The type of the property you are creating
    typeof(MyClass), 	// The type of your containing class
    false, 		// The default value of the property you are creating
    propertyChanged: (BindableObject bindable, object old_value, object new_value) => 
    	((MyClass)bindable).UpdateFooBar((bool)old_value, (bool)new_value);

/// Used to set your property programatically
public bool FooBar
        return (bool)GetValue(FooBarProperty);
        SetValue(FooBarProperty, value);

/// Called when the value of your property has been updated
/// Note that this method is only called when the property has CHANGED, not
/// if it has been set to the same value - take not of the default value!
private void UpdateFooBar( bool old_value, bool new_value )
    // Do whatever you need to do when the property 
    // has been set here. By the time this method is
    // called FooBar will already hold the updated value

If you found this helpful I always appreciate more followers on Twitter!

How To Use Google Maps In Xamarin.Forms

Recently I’ve been putting together an app development proposal for a potential client. It’s the sort of app that I think would suit Xamarin.Forms very well, only it has a large mapping component for which the client wants to use Google Maps on both Android and iOS.

At the time of writing the ‘built in’ Xamarin.Forms Map view has limited functionality and defaults to using Apple Maps on iOS. This makes it unsuitable for this project which meant I had to find and (roughly) test out an alternative before I could put a proposal together with any degree of confidence.

I managed to get it working in the end, but not without hitting all sorts of snags which I’ll document here in the hope it might make the process easier for someone else. Most of this information is scattered about the web but it’s difficult to find it all in one place.

1. Find A Suitable Library
Fortunately there’s a third-party open source Google Maps API in development for Xamarin forms which you can access here. Xamarin.Forms.GoogleMaps seems to be pretty full-featured so, rather than trying to reinvent the wheel, this is what I decided to use. Thanks very much to GitHub user amay077 for making this available.

2. Get It To Compile
Once downloaded from GitHub the next step is to get the Xamarin.Forms.GoogleMaps sample project to compile. This was pretty straightforward apart from a few error messages – you may run into the following on iOS:

This version of Xamarin.iOS requires the iOS 10.2 SDK (shipped with Xcode 8.2) when the managed linker is disabled. Either upgrade Xcode, or enable the managed linker. (MT0091) (XFGoogleMapSample.iOS)

To get round this either upgrade Xcode (groan) or do what I did and go to Project Options->Build->iOS Build and set linker behaviour to ‘Link Framework SDKs only’ which should fix it (you may have to clean and rebuild).

On Android you may get something like the following:

Could not find android.jar for API Level 23. This means the Android SDK platform for API Level 23 is not installed. Either install it in the Android SDK Manager (Tools > Open Android SDK Manager…), or change your Xamarin.Android project to target an API version that is installed.

A rare helpful error message this – to fix either do as the message says and go to Tools->SDK Manager and install the appropriate level SDK or go to Project Options->Build->General and select an SDK that you do have installed (I set it to Android 5.0 and it worked fine).

3. Install Google Maps On A GenyMotion Device
OK – I’m going to assume that a) you want to use an emulator for development and b) you are using GenyMotion as it’s by far the fastest. If you try and run the Xamarin.Forms.GoogleMaps sample project as is you will probably see a grey square where the map should be with ‘Xamarin.Forms.GoogleMaps’ in black text. This is because Google Play Services (which includes Google Maps) is not installed on GenyMotion by default. To do this I followed the instructions here (scroll down the page to where it says ‘Setup Google Play Services’). I was using an Android 5.0 GenyMotion device and did not need to do the first step (ARM Translation Installer).

Once you have flashed your virtual device you will get all sorts of irritating popup messages saying ‘Google Play Services Has Stopped’ and the like but if you just soldier on through this and update google play services and google maps via Google Play you should be OK. If you can get the standard Google Maps app running on the device you are sorted.

4. Create An Android API Key
So, assuming you have Google Maps running OK on your GenyMotion emulator, if you now try and run the Xamarin.Forms.GoogleMaps sample project you will just get what looks like a blank map (or a ‘barren featureless desert’ for Black Adder fans). This is because you haven’t supplied a valid API key – if you look through the Application Output of the app in Xamarin Studio you will see something like the following:

Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
In the Google Developer Console (https://console.developers.google.com)
Ensure that the “Google Maps Android API v2” is enabled.
Ensure that the following Android Key exists:
API Key: your_google_maps_android_api_v2_api_key
Android Application (;): FF:4B:77:38:AB:3A:F3:A8:42:CC:03:27:74:AA:CB:5F:66:A1:5F:D0;net.amay077.xfgooglemapsample

Copy the long hex string (SHA-1 certificate) and package name from this error message as this will save you faffing around with keystore commands later.

Now go to your Google Developer Console. On your Dashboard click ‘Enable API’ and select the Google Maps Android SDK. Now go to ‘Credentials’, click on ‘Create Credentials’ and select ‘API Key’ followed by ‘Restrict Key’.

You should now get a list of restriction options. Select ‘Android apps’ and enter the package name and SHA-1 certificate from the error message I told you to note down earlier. The API key can now be saved.

Note that you will have to enable access for both the ‘Debug’ and ‘Release’ versions of your app as they are signed differently and therefore have a different SHA-1 certificate. Simply run the app in both configurations and grab the application output as above to get the appropriate SHA-1 key for each.

Whilst you’re at it you may want to create an iOS API key (see step 5). It takes a few minutes for these to take effect so, once done, I suggest you go and make yourself a well-earned cup of coffee.

Now you need to embed your API key in your app. The way I suggest doing this is consistent with all the documentation on the matter – go to your AndroidManifest file and enter the following inside the tag:

<meta-data android:name=”com.google.android.geo.API_KEY” android:value=”YOUR_API_KEY” />
<meta-data android:name=”com.google.android.gms.version” android:value=”@integer/google_play_services_version” />

Replace ‘YOUR_API_KEY’ with your actual API key of course. Now your manifest file should look something like this:

<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221; android:versionCode=”1″ android:versionName=”1.0″ package=”net.amay077.xfgooglemapsample”>
<uses-sdk android:minSdkVersion=”15″ />
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_LOCATION_EXTRA_COMMANDS” />
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />
<uses-permission android:name=”android.permission.ACCESS_CHECKIN_PROPERTIES” />
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
<uses-permission android:name=”android.permission.ACCESS_MOCK_LOCATION” />
<uses-permission android:name=”android.permission.INTERNET” />
<application android:label=”OpenHouse”>
<meta-data android:name=”com.google.android.geo.API_KEY” android:value=”AIzaSyDJ7qxHOOh_4A1PodKyU0MlkhFIsyZsNJ7″ />
<meta-data android:name=”com.google.android.gms.version” android:value=”@integer/google_play_services_version” />

Just one more step – in the Xamarin.Forms.GoogleMaps sample project the API key isn’t entered in this way so you will need to delete the ‘dummy’ API key that been placed there. Do do this simply open MyApp.cs and remove the following line:


Hopefully if you now rebuild and run the Android project, and you’ve waited long enough for your API key to activate, you should now be able to see Google Maps correctly displayed in the GenyMotion emulator. Well done – it’s not the simplest process in the world!

5. Create An iOs API Key
This is pretty much the same process as creating your Android API key. Go to your Google Developer Console. On your Dashboard click ‘Enable API’ and this time select the Google Maps iOS SDK. Again go to ‘Credentials’, click on ‘Create Credentials’ and select ‘API Key’ followed by ‘Restrict Key’. This time choose iOS app restriction and enter the bundle identifier from your Info.plist file. For the Xamarin.Forms.GoogleMaps sample project it’s ‘net.amay077.xfgooglemapsample’.

To embed the API key into your iOS application open AppDelegate.cs and pass the API key as a string in the call to Xamarin.FormsGoogleMaps.Init(). This should be all you need to get the app running on iOS.

6. Embed The Xamarin.Forms.GoogleMaps API In Your Own Projects
Assuming you’ve managed to run the sample project successfully it should be fairly simple to get the API working in your own Xamarin.Forms projects. Xamarin.Forms.GoogleMaps is in NuGet so, in a new Xamarin.Forms solution, right-clicking on the ‘packages’ folder and selecting ‘Add Package’ will allow you to add references to the Xamarin.Forms.GoogleMaps packages. Remember to add them to every project in your solution. You may need to enable ‘show pre-release packages’ in the NuGet browser in order to download versions that are consistent with the sample projects.

If you run into strange issues, such as XAML errors when setting properties on a Xamarin.Forms.GoogleMaps.Map view or ‘Could Not Resolve Type’ and ‘BadImageFormatException’ errors when trying to position the map then you most likely have an incompatible version of the various packages somewhere. Check that all your package references (both to Xamarin.Forms and Xamarin.Forms.GoogleMaps) are consistent in all of your projects and ideally the same as the sample project.

I hope this article saves you some of the pain and grief I endured whilst trying to get all the stuff to work. If it does I always appreciate more followers on Twitter here!

FAIL – Google Maps Not Installed On GenyMotion Emulator

FAIL – No Valid Google Maps API Key

SUCCESS – Xamarin.Forms.GoogleMaps Working on GenyMotion Emulator

Creating Bindable Properties in Xamarin.Forms

UPDATE: This post, popular as it has been, is somewhat outdated now. I’ve written an updated version that is more ‘cut and paste’ friendly and removes the references to generic types (which are now deprecated in Xamarin.Forms) here.

Something you’re bound to run into sooner or later when developing with Xamarin.Forms is the issue of how to make a property bindable. Fortunately it’s pretty easy to do – though I found it hard to find a simple example online that worked both for setting the property programmatically and via xaml.

So, without further ado here’s an example of a bindable ‘Foobar’ property that can be set both programmatically and via xaml. Just copy/paste this into your own code whilst changing the relevant bits and you should be fine…

Note: ‘YourClass’ should be replaced by the type name of the class that holds the property. References to ‘bool’ should (obviously) replaced by the type of property you are declaring. The ‘false’ value that is passed to the BindableProperty.Create() method refers to the default value for the property and should be replace by something meaningful.

public static readonly BindableProperty FoobarProperty=BindableProperty.Create( p => p.Foobar, false );

public bool Foobar
		return (bool)GetValue(FoobarProperty); 
		SetValue(FoobarProperty, value); 

private void UpdateFoobar()
	// Do whatever you need to do when the property 
	// has been set here. By the time this method is
	// called Foobar will already hold the updated value
	// so if you need to reference the old value you will
	// need to store it in a class variable

protected override void OnPropertyChanged(string propertyName)

	switch( propertyName )
		case "Foobar":

Hopefully that’s been helpful – now why not take a brief break from work to watch our trailer for ‘Attack Of Giant Jumping Man’…

Attack of Giant Jumping Man

Unhelpful Exceptions In Xamarin.Forms

if you’re wondering why it’s been so quiet around here recently it’s because I’ve had my head down working on a contract project using Xamarin Forms – as well as trying to get #superjp finished. Life is busy. Too busy.

Anyway, Xamarin Forms is pretty cool once you get the hang of it – but to start with things were very painful. Documentation is sparse and often wrong, then when crashes happen exceptions are usually thrown deep within the bowels of some auto-generated code leaving you with little or no idea what the issue is. And that’s when you get an exception at all – often the exceptions are unhelpfully caught and just ‘glossed over’, leaving you with absolutely no idea why your code isn’t executing.

So I thought I’d jot down a few posts covering issues I’ve run up against which may prevent someone from tearing their hair out quite as much as I had to over the first couple of weeks – first up is weird crashes and unhelpful exceptions.

1. Autofac.Core.DependencyResolutionException

An exception was thrown while invoking the constructor ‘Void .ctor(IAuthenticationService)’ on type ‘MenuService’. Argument cannot be null.

This exception often appears after changing properties in the XAML. It appears to be the result of a bug in Xamarin Forms and was always thrown in the same place in our code. Simply building/running again stopped the exception from appearing. Annoying to say the least – but once you’ve added a comment to remind you it’s not your fault you learn to live with it.

2. Error: The type `SomeType’ already contains a definition for `someProperty’
This is a compile time rather than a runtime error and is caused by creating properties in your ‘code behind’ class that have the same names as controls in the associated XAML (x:Name=”someProperty”). Always give your custom properties/class variables unique names – Xamarin.Forms seems to use the ‘x:Name’ property for variable names in generated code and this is what causes the conflicts.

A similar issue can cause errors at runtime if you have a named control (x:Name=”SomeProperty”) that conflicts with a type name in the same namespace or one of the imported namespaces. It’s probably good practice to define your own naming convention for XAML controls so that you are sure they don’t conflict with any properties, types or variables in any accessible namespace.

3. Xamarin.Forms.Xaml.XamlParseException: Property Content is null or is not IEnumerable
This one is probably obvious to those with prior experience of XAML but to noobs like me it wasn’t and caused much weeping and gnashing of teeth. You can’t have more than one Layout at the top level of a ContentPage (or ScrollView, whatever). This makes sense when you think about it (how would it know how to layout the Layouts) but the exception doesn’t give much clue as to what’s going on so can lead to confusion.

4. Xamarin.Forms.Xaml.XamlParseException: No Property of name ‘Foobar’ found
Assuming the class to which you’re referring actually has a property of name ‘Foobar’ (or whatever) then the most likely cause of this is that the property is not bindable. I’ve given a simple example of how to make a property bindable here. Most of the properties within the Xamarin.Forms classes have already been made bindable but if you do run into one that’s not you can most likely create a subclass that contains a bindable version of the property you want to access (just set the appropriate property in the base class).

This error can also be caused by duplicate name issues as describe in 2 above.

5. The name InitializeComponent does not exist within the current context
If you’re running Forms as a shared project with iOS as the target the most likely reason for this error is that you don’t have ‘Use MSBuild Build Engine’ checked under Project Options->Build->General.

Another cause of this error can be mistakenly not having your XAML class definition ( x:Class=”Foo.Bar”) matching the class definition in your ‘code behind’ class. I made this mistake a number of times when using copy/paste to set up XAML files.

I may add more here later…