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

Xamarin WinUI XAML

6 years ago

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:
<Entry x:Name="Vid"/>
<Button Text="Search" Pressed="SearchPressed" />

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

void SearchPressed( object sender )
{
   Application.Current.MainPage = new AnotherPage( Vid.Text );
}

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!

void SearchPressed( object sender ) // <- something is missing here!

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

void SearchVideo( object sender, EventArgs e )

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

Takeaway

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 :-) .