Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug Xamarin.Forms XAML

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?

like image 751
AQuirky Avatar asked Jul 05 '26 05:07

AQuirky


1 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.

like image 88
Vyvianite Avatar answered Jul 06 '26 20:07

Vyvianite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!