1
votes

I am using visual studio 2017 to create the default Xamarin Forms PCL project in C#. If I make any error in the XAML the InitializeComponent() call hangs. There are no editor, compiler, builder, or run-time errors. Is there a way to research the cause of the error? I'm pretty sure Visual Studio 2015 threw a run-time error.

Here is an example with a reference to a missing style. This causes InitializeComponent() to hang. I am using the VisualStudio_android-23_x86_phone emulator and VS does the same thing for every emulator I've tried and also my Samsung Note 4. Thanks.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Broken"
             x:Class="Broken.MainPage">
    <Label Text="Welcome to Xamarin Forms!" 
           VerticalOptions="Center" 
           HorizontalOptions="Center"
           Style="{StaticResource myStyle}"/>

</ContentPage>
3
What is the error? - Adam
I'm having the same problem. It's not only that the ap hangs, the whole IDE is also having problems. With every time this happens, the IDE starts hugging one of my (virtual) CPU cores. after 8 runs I have 100% cpu usage even when the app is not running anymore until I restart Visual Studio. :( - Adrian Grigore

3 Answers

5
votes

The answer is remarkably simple. Put InitializeComponent inside a try/catch. Even though InitializeComponent does not return when it detects a XAML parse error, you can catch the exception and the ex.message is useful.

try
            {
                InitializeComponent();
            }
            catch (Exception ex)
            {
                throw ex;
            }

Displays the message "Xamarin.Forms.Xaml.XamlParseException: Position 9:12. StaticResource not found for key myStyle". I wasn't expecting the exception to be caught, but I was serendipitously wrong.

Thanks to Stephane for the "swallow" clue.

0
votes

You can enable XAML Compilation to catch errors with your XAML at compile time instead of runtime.

0
votes

If there's an error in your XAML, an exception is thrown. The problem is that Android often swallow the exception resulting into a crash.

You can try to break when a XamlParseException is thrown. That should get you to the point just before the crash.

As you figured, XAML is not validated at compile time, but only at runtime. However, if you turn on XamlC (https://developer.xamarin.com/guides/xamarin-forms/xaml/xamlc/), (most of) the parsing errors will be found at compile time. And that's not the only argument for using XamlC.