首页 > 解决方案 > 外壳导航

问题描述

我有一个登录/注册页面,我希望能够像在 Web 应用程序中一样在它们之间导航路由导航 (//LoginPage)。我真的不能让它工作。我已经构建了一个 AppShell.xaml 页面,并且我已经在 App.xaml.cs 中注册了我的 LoginPage 和 RegisterPage(我也尝试在 AppShell.xaml.cs 中注册它们)并且我有一个视图模型,它有 2 个用于在登录和注册页面,但是当我单击按钮导航时,我得到了这个

System.NullReferenceException:“对象引用未设置为对象的实例。”

这是我的视图模型

namespace Appointments.ViewModels
{
    public class RegLogViewModel : BaseViewModel
    {
        public AsyncCommand GoToRegisterCommand { get; }
        public AsyncCommand GoToLoginCommand { get; }
        public RegLogViewModel()
        {
            GoToLoginCommand = new AsyncCommand(GoToLogin);
            GoToRegisterCommand = new AsyncCommand(GoToRegister);
        }
async Task GoToRegister()
        {
            await Shell.Current.GoToAsync($"//{ nameof(RegisterPage)}");
        }

        async Task GoToLogin()
        {
            await Shell.Current.GoToAsync($"//{ nameof(LoginPage)}");
        }   
}

我的 AppShell.xaml

<Shell xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Appointments.AppShell"
             xmlns:views="clr-namespace:Appointments.Views">

     //// I HAVE TRIED WITH AND WITHOUT THIS  SHELLCONTENT\\\\\

    <ShellContent Route="LoginPage" ContentTemplate="{DataTemplate views:LoginPage}"/>
    <ShellContent Route="RegisterPage" ContentTemplate="{DataTemplate views:RegisterPage}"/>
</Shell>

我的 AppShell.xaml.cs

namespace Appointments
{

    public partial class AppShell : Shell
    {
        public AppShell()
        {
            InitializeComponent();
        }
    }
}

我的 App.xaml.cs

namespace Appointments
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
 
            MainPage = new LoginPage();
        }
    }
}

和 Login.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:viewmodels="clr-namespace:Appointments.ViewModels"
             x:DataType="viewmodels:RegLogViewModel"
             x:Class="Appointments.Views.LoginPage">

    <ContentPage.Content>
        <StackLayout>
            <Label 
                Text="Login Page!"
                FontSize="Title"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
            
            <Label
                Text="{Binding Name}"/>

            <Entry
                Text="{Binding Name}"/>

            <Button
                Text="Go To Registration"
                Command="{Binding GoToRegisterCommand}"/>
            
            <ActivityIndicator IsRunning="{Binding IsBusy, Mode=OneWay}"/>
        </StackLayout>

    </ContentPage.Content>
</ContentPage>

标签: c#xamlxamarin.forms

解决方案


问题是在 App.xaml.cs 我有

MainPage = new LoginPage();

但我不得不使用

MainPage = new AppShell();

它会工作,但现在我不明白应用程序如何知道首先打开我的 LoginPage 而不是 RegisterPage 或任何其他页面


推荐阅读