How to debug Xamarin.Forms XAML

Viewed 1596

I'm finding Xamarin.Forms XAML very frustrating.

If I use this syntax...

<ContentView.Resources>
    <local:MyConverter1 x:Key="MyConverter1"/>
</ContentView.Resources>

I will get a System.NullReferenceException from InitializeComponent(). Nothing in the stack trace or output window or anywhere else tells me what is wrong.
Note: this syntax works fine in WPF.

After a lot of struggle I discovered I need this syntax...

<ContentView.Resources>
    <ResourceDictionary>
        <local:MyConverter1 x:Key="MyConverter1"/>
    </ResourceDictionary>
</ContentView.Resources>

Likewise for ListView DataTemplate. This throws null reference exception...

            <ListView.ItemTemplate>
                <DataTemplate>
                    <Label Text="{Binding Converter={StaticResource MyConverter1}}"/>
                </DataTemplate>
            </ListView.ItemTemplate>

Because the proper syntax is this...

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Label Text="{Binding Converter={StaticResource MyConverter1}}"/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>

Again this syntax works fine in WPF. I fully realize that Xamarin.Forms is not WPF but I getting weary of being sucker punched by null reference exceptions whenever I use a XAML construct that is valid in WPF.

What is the best way to debug Xamarin.Forms XAML issues?

Right now I am simply commenting stuff out until it starts working. This is akin to putting print statements in imperative code. Declarative code is supposed to be superior to imperative code.

What am I doing wrong?

3 Answers

Yeah, there isn't really a good way of debugging XAML. Turning on Xaml compilation will help. It compiles all your forms code into IL which makes it faster and finds these sorts of problems at compile time. You may also want to look into the new c# markup extensions. They are still in beta, but they let you write your declarative ui in straight c# with full intellisense.

Also, you may wish to switch from using ListView to using the newer CollectionView. It's much more performant and is basically an in-place upgrade. More info here.

I normally have 2 steps

  1. add a try catch in code behind

    using System; using System.Diagnostics; using Xamarin.Forms;

    namespace TestApp.Views { public partial class AssetsPage : ContentPage { public WelcomePage() { try { InitializeComponent(); } catch (Exception ex) { Debug.WriteLine(ex); } } } }

  2. Remove code and keep on checking if the problem disappears

not really a magic solution but it helps the most especially when you have large groups of complicated code

Related