mkamin15
mkamin15

Reputation: 37

Invalid Cast Exception on Xamarin.Forms app

I created a new Xamarin.Forms mobile app and the only thing I did was replace the default welcome to xamarin label in the .xaml file with:

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

The previewer doesn't work on either android or ios preview, and when I run the program I get a System.InvalidCastException on this line of code, that is already in the pregenerated code: global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(ticTactTestPage));

I'm still a beginner so I did some goole searching on this, and most of the time the exception is thrown in code written by the developer, however in this case I haven't touched anything except deleting <Label Text="Welcome to Xamarin!"/> from the .xaml file. Can anyone help solve this?

Edit 1: A user suggested moving the labels inside of the <Grid><Grid/> since I originally had them outside. However, the issue still remains.

Upvotes: 1

Views: 906

Answers (1)

SushiHangover
SushiHangover

Reputation: 74094

You have an extra > at the end of your ColumnDefinition Widths elements:

<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 Compilation

To catch most of these types of typos in XAML, you can enable the XAML compiler (XAMLC).

XAMLC offers a number of a benefits:

  • It performs compile-time checking of XAML, notifying the user of any errors.
  • It removes some of the load and instantiation time for XAML elements.
  • It helps to reduce the file size of the final assembly by no longer including .xaml files.

Assembly level:

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

Class level:

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

Upvotes: 2

Related Questions