xamarin 表单 InitializeComponent 挂起

use*_*319 1 c# android xamarin xamarin.forms

我正在使用 Visual Studio 2017 在 C# 中创建默认的 Xamarin Forms PCL 项目。如果我在 XAML 中犯任何错误, InitializeComponent() 调用就会挂起。没有编辑器、编译器、构建器或运行时错误。有没有办法研究错误的原因?我很确定 Visual Studio 2015 抛出了一个运行时错误。

这是一个引用缺失样式的示例。这会导致 InitializeComponent() 挂起。我正在使用 VisualStudio_android-23_x86_phone 模拟器,VS 对我尝试过的每个模拟器以及我的三星 Note 4 都做同样的事情。谢谢。

<?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>
Run Code Online (Sandbox Code Playgroud)

use*_*319 5

答案非常简单。将 InitializeComponent 放在 try/catch 中。即使 InitializeComponent 在检测到 XAML 解析错误时不返回,您也可以捕获异常并且 ex.message 很有用。

try
            {
                InitializeComponent();
            }
            catch (Exception ex)
            {
                throw ex;
            }
Run Code Online (Sandbox Code Playgroud)

显示消息“Xamarin.Forms.Xaml.XamlParseException:位置 9:12。未找到键 myStyle 的静态资源”。我没想到异常会被捕获,但我意外地错了。

感谢 Stephane 的“燕子”线索。