Xamarin.Forms and the case of x:Name-killing event

I have come across an interesting Xamarin.Forms problem on StackOverflow which I casually called “Xamarin.Forms and the case of x:Name-killing event”.

Xamarin logo

The OP had a innocently looking Xamarin.Forms page, with the following content:

And in the code-behind, the SearchPressed method was implemented like this:

The problem was very simple but very surprising. When the user clicked the button, x:Name Vid inside the SearchPressed handler was null.

At first I thought the problem may be that the page is not properly initialized, whereas the OP then assured me, that after InitializeComponent() call in the constructor Vid was definitely not null. So it had to change to null sometime in between the constructor and event handler call. To make things even more interesting, the code worked perfectly on Android, but crashed on UWP only.

I have been able to replicate the problem on my PC which ruled out the “repair/uninstall Visual Studio and Xamarin” cycle and I couldn’t understand what was happening. It didn’t make sense, the code was plain and simple and there were no additional bells and whistles.

Only after exceedingly long staring into the code I saw it. The event handler. The event handler!

Of course! Every good event handler has an EventArgs parameter! This is how the event handler should look like:

This one little change and the Vid was no longer null and everything suddenly worked as expected.


A problem like this is very hard to debug. Especially when it works perfectly on one platform and fails on another. Luckily this concrete issue can be overcome quite easily – by using the XAML IntelliSense in Visual Studio to let it generate the appropriate event handling method automatically. This is usually faster, more convenient and saves you from unwelcome surprises 🙂 .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">