【问题标题】:Invalid Cast Exception on Xamarin.Forms appXamarin.Forms 应用程序上的无效转换异常
【发布时间】:2018-03-11 10:44:18
【问题描述】:

我创建了一个新的 Xamarin.Forms 移动应用程序,我唯一做的就是将 .xaml 文件中的默认 Welcome to xamarin 标签替换为:

    <Grid Margin="0,20,0,0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>>
            <ColumnDefinition Width="*"/>>
            <ColumnDefinition Width="*"/>>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
    </Grid.RowDefinitions>


    <Label Text="You are: (X)" Grid.Row="0" Grid.Column="0" Margin="5"/>
    <Label Text="Your opponent is: (O)" Grid.Row="0" Grid.Column="2" Margin="5" HorizontalTextAlignment="End"/>
    </Grid>

预览器不适用于 android 或 ios 预览,当我运行程序时,我在这行代码中得到一个 System.InvalidCastException,它已经在预生成的代码中:global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(ticTactTestPage));

我还是一个初学者,所以我对此进行了一些 goole 搜索,并且大多数时候异常是在开发人员编写的代码中引发的,但是在这种情况下,我除了删除 &lt;Label Text="Welcome to Xamarin!"/&gt; 之外什么都没做.xaml 文件。谁能帮忙解决这个问题?

编辑 1:用户建议将标签移动到 &lt;Grid&gt;&lt;Grid/&gt; 内部,因为我最初将它们放在外面。但是,问题仍然存在。

【问题讨论】:

  • 从非常简短的代码来看,您的标签似乎在 之外,这可能是您的问题的原因
  • @Ale_lipa 感谢您的回复,我更改了代码,以便标签在里面并且没有运气。同样的结果。我要更新问题,所以没有其他人提供该解决方案。再次感谢。
  • 另一件事是您的 ColumnDefinitions 有问题(例如 ColumnDefinition Width="*"/>>)。删除第二个右括号'>'
  • 从列定义中删除多余的 > >
  • 代码现在运行,我是个傻瓜哈哈。谢谢。

标签: c# xamarin xamarin.forms


【解决方案1】:

在 ColumnDefinition Widths 元素的末尾有一个额外的 &gt;

<Grid Margin="0,20,0,0">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="100"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
</Grid>
<Label Text="You are: (X)" Grid.Row="0" Grid.Column="0" Margin="5"/>
<Label Text="Your opponent is: (O)" Grid.Row="0" Grid.Column="2" Margin="5" HorizontalTextAlignment="End"/>

XAML 编译

要在 XAML 中捕获大多数此类拼写错误,您可以启用 XAML 编译器 (XAMLC)。

XAMLC 提供了许多好处:

  • 它执行 XAML 的编译时检查,通知用户任何错误。
  • 它消除了 XAML 元素的一些加载和实例化时间。
  • 它不再包含 .xaml 文件,有助于减小最终程序集的文件大小。

装配级:

~~~~
[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace PhotoApp
~~~~

班级等级:

[XamlCompilation (XamlCompilationOptions.Compile)]
public class HomePage : ContentPage
{
  ~~~

【讨论】:

  • @MatthewKaminski 您应该启用 XAMLC 在编译时捕获这些类型的错误... ;-)
猜你喜欢
  • 1970-01-01
  • 2017-05-18
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多