简体   繁体   中英

Xamarin navigating pages not working ( MVVM )

MainPage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TravelRecordApp.MainPage"
             xmlns:View="clr-namespace:TravelRecordApp.View">

    <View:MainView/>

</ContentPage>

MainView.xaml

<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TravelRecordApp.View.MainView"
             xmlns:ViewModel="clr-namespace:TravelRecordApp.ViewModel">

    <ContentView.BindingContext>
        <ViewModel:MainViewModel/>
    </ContentView.BindingContext>  
    
        <StackLayout ..>
            <Entry ../>
            <Entry ../>
            <Button Command="{Binding LoginCommand}"/>
        </StackLayout>
</ContentView>

app.xaml.cs

public App()
{
    InitializeComponent();

    MainPage = new NavigationPage(new MainPage());
    //Also Tried MainPage = new MainPage();
}

MainViewModel.cs

public void Login()
{
    bool isEmailEmpty = string.IsNullOrEmpty(EmailEntry);
    bool isPasswordEmpty = string.IsNullOrEmpty(PasswordEntry);

    if (isEmailEmpty || isPasswordEmpty)
    {
        
    }
    else
    {
        Navigation.PushAsync(new HomePage());
    }
}

HomePage.xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TravelRecordApp.View.HomePage">
    <StackLayout>
            <Label Text="Hello, this is main page" />
        </StackLayout>
</ContentPage>

The Problem Is:

When I debugged the code, I can see it reaches Navigation.PushAsync(new HomePage()); after clicking the button, but nothing happens after this point. It's not opening the Home Page.

  1. As Jason said, you can try to use App.Current.MainPage.Navigation.PushAsync(new HomePage());

  2. Using "Xamarin.Forms Shell" navigation is a great way to navigate between pages. For details, please refer to: https://learn.microsoft.com/en-us/xamarin/xamarin.forms/app-fundamentals/shell/navigation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM