Xamarin.Forms:应用程序未在页面上显示元素

问题描述

我目前正在学习使用Xamarin.Forms和C#(进入它的第一周),并且正在尝试创建一个基本的登录应用程序。
我从一个空白模板开始。现在,当我运行我的应用程序时,仅弹出基本屏幕,而不弹出页面中的元素。怎么了?

App.xaml.cs

using Xamarin.Forms;

namespace XamarinApp
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            new LoginPage();
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
    }
}


LoginPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamarinApp.LoginPage">
    <ContentPage.Content>
        <StackLayout>
            <Label 
                Text="Welcome"
                />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

LoginPage.xaml.cs

using Xamarin.Forms;

namespace XamarinApp
{
    public partial class LoginPage : ContentPage
    {
        public LoginPage()
        {
            InitializeComponent();
        }

    }
}

解决方法

TL-DR

我相信要解决您的问题,您需要更改线路:

new LoginPage();

收件人:

MainPage = new LoginPage();

我的推理

您需要指定MainPage是什么。初次使用时,这部分可能会造成混淆,因为提供的示例页面也称为MainPage,但是其中一个是class/Page实现,而另一个关键部分是{{ {} {1}}类继承的1}}类。这样应用程序在运行时就知道它正在Application内启动。

通常,当您创建一个新的Blank Xamarin.Forms应用程序时,您将在App.xaml.cs中看到以下代码

App

我怀疑您以某种方式添加到LoginPage中的更改最终从该行中删除了关键部分:Page