Не могу добавить новую пустую страницу в Xamarin - PullRequest
1 голос
/ 10 апреля 2020

У меня уже есть приложение Xamarin, но теперь я хочу добавить страницу регистрации / входа в систему при запуске. Когда я открываю приложение, сначала открывается страница регистрации.

Я добавляю пустую страницу с заголовком «Добро пожаловать в приложение» и добавляю кнопку, но кнопка не работает и работает только при использовании навигации по другим страницам, почему? и как добавить форму регистрации на пустой странице?

ИЗОБРАЖЕНИЕ: Теперь это выглядит следующим образом.

Я хочу удалить эти учетные данные , Accounts et c сверху и просто пустая страница регистрации.

Вот код, надеюсь, он поможет вам лучше понять его. Если вам нужно что-то еще, просим об этом.

Спасибо:)

ОБНОВЛЕНИЕ: @ Jason Comment : я удалил код входа из MainPage. xml, теперь вкладки навигации больше не отображаются, но теперь кнопка не работает (когда я нажимаю на нее, ничего не происходит).

enter image description here

LoginPage. xml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:converters="clr-namespace:Osma.Mobile.App.Converters;assembly=Osma.Mobile.App"
    xmlns:behaviours="clr-namespace:Osma.Mobile.App.Behaviors;assembly=Osma.Mobile.App"
    xmlns:components="clr-namespace:Osma.Mobile.App.Views.Components;assembly=Osma.Mobile.App"
    x:Class="Osma.Mobile.App.Views.Login.LoginPage"
    Title="Login"
    xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
    ios:Page.LargeTitleDisplay="Always"
>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to App"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
            <Button Text="Enter"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand"
                Command="{Binding ButtonClickedCommand}"
                />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

LoginPage. xml .cs

using System;
using System.Collections.Generic;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Osma.Mobile.App.Views.Login
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        public LoginPage()
        {
            InitializeComponent();
        }
    }
}

LoginViewMode.cs

using System;
using System.Reactive.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using System.Threading.Tasks;
using Acr.UserDialogs;
using Hyperledger.Aries.Contracts;
using Hyperledger.Aries.Features.DidExchange;
using Hyperledger.Aries.Utils;
using Osma.Mobile.App.Events;
using Osma.Mobile.App.Extensions;
using Osma.Mobile.App.Services;
using Osma.Mobile.App.Services.Interfaces;
using ReactiveUI;
using Xamarin.Forms;
using Xamarin.Essentials;
using Osma.Mobile.App.ViewModels.Credentials;

namespace Osma.Mobile.App.ViewModels.Login
{
    public class LoginViewModel : ABaseViewModel
    {
        private readonly ICustomAgentContextProvider _agentContextProvider;
        private readonly IConnectionService _connectionService;

        public LoginViewModel(
            IUserDialogs userDialogs,
            INavigationService navigationService,
            ICustomAgentContextProvider agentContextProvider,
            IConnectionService defaultConnectionService) :
            base("Login", userDialogs, navigationService)
        {
            _agentContextProvider = agentContextProvider;
            _connectionService = defaultConnectionService;
        }

        public ICommand ButtonClickedCommand => new Command(async () => await NavigationService.NavigateToAsync<CredentialsViewModel>());
    }
}

App.xaml. css

using System.Threading.Tasks;
using Autofac;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Osma.Mobile.App.Services.Interfaces;
using Osma.Mobile.App.Utilities;
using Osma.Mobile.App.ViewModels;
using Osma.Mobile.App.ViewModels.Login;
using Osma.Mobile.App.ViewModels.Account;
using Osma.Mobile.App.ViewModels.Connections;
using Osma.Mobile.App.ViewModels.CreateInvitation;
using Osma.Mobile.App.ViewModels.Credentials;
using Osma.Mobile.App.Views;
using Osma.Mobile.App.Views.Login;
using Osma.Mobile.App.Views.Account;
using Osma.Mobile.App.Views.Connections;
using Osma.Mobile.App.Views.CreateInvitation;
using Osma.Mobile.App.Views.Credentials;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml;
using LoginPage = Osma.Mobile.App.Views.Login.LoginPage;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace Osma.Mobile.App
{
    public partial class App : Application
    {
        public new static App Current => Application.Current as App;
        public Palette Colors;

        private readonly INavigationService _navigationService;
        private readonly ICustomAgentContextProvider _contextProvider;

        public App(IContainer container)
        {
            InitializeComponent();

            MainPage = new LoginPage();

            Colors.Init();
            _navigationService = container.Resolve<INavigationService>();
            _contextProvider = container.Resolve<ICustomAgentContextProvider>();

            InitializeTask = Initialize();
        }

        Task InitializeTask;
        private async Task Initialize()
        {
            //Pages
            _navigationService.AddPageViewModelBinding<MainViewModel, MainPage>();
            _navigationService.AddPageViewModelBinding<LoginViewModel, LoginPage>();
            _navigationService.AddPageViewModelBinding<ConnectionsViewModel, ConnectionsPage>();
            _navigationService.AddPageViewModelBinding<ConnectionViewModel, ConnectionPage>();
            _navigationService.AddPageViewModelBinding<RegisterViewModel, RegisterPage>();
            _navigationService.AddPageViewModelBinding<AcceptInviteViewModel, AcceptInvitePage>();
            _navigationService.AddPageViewModelBinding<CredentialsViewModel, CredentialsPage>();
            _navigationService.AddPageViewModelBinding<CredentialViewModel, CredentialPage>();
            _navigationService.AddPageViewModelBinding<AccountViewModel, AccountPage>();
            _navigationService.AddPageViewModelBinding<CreateInvitationViewModel, CreateInvitationPage>();

            if (_contextProvider.AgentExists())
            {
                await _navigationService.NavigateToAsync<LoginViewModel>();
            }
            else
            {
                await _navigationService.NavigateToAsync<LoginViewModel>();
            }
        }

        protected override void OnStart()
        {
            #if !DEBUG 
                AppCenter.Start("ios=" + AppConstant.IosAnalyticsKey + ";" +
                                "android=" + AppConstant.AndroidAnalyticsKey + ";",
                        typeof(Analytics), typeof(Crashes));
            #endif
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

MainPage. xml

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:connections="clr-namespace:Osma.Mobile.App.Views.Connections;assembly=Osma.Mobile.App"
    xmlns:credentials="clr-namespace:Osma.Mobile.App.Views.Credentials;assembly=Osma.Mobile.App"
    xmlns:account="clr-namespace:Osma.Mobile.App.Views.Account;assembly=Osma.Mobile.App"
    xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
    x:Class="Osma.Mobile.App.Views.MainPage"
    CurrentPageChanged="CurrentPageChanged"
    Appearing="Appearing"
>
    <connections:ConnectionsPage
        Icon="connection_icon.png"
        ios:NavigationPage.PrefersLargeTitles="true"
        BindingContext="{Binding Connections}">
    </connections:ConnectionsPage>
    <credentials:CredentialsPage
        Icon="credentials_icon.png"
        ios:NavigationPage.PrefersLargeTitles="true"
        BindingContext="{Binding Credentials}">
    </credentials:CredentialsPage>
    <account:AccountPage
        Icon="account_icon.png"
        ios:NavigationPage.PrefersLargeTitles="true"
        BindingContext="{Binding Account}">
    </account:AccountPage>
</TabbedPage>

MainViewModel.cs

using System.Threading.Tasks;
using Acr.UserDialogs;
using Osma.Mobile.App.Services.Interfaces;
using Osma.Mobile.App.ViewModels.Login;
using Osma.Mobile.App.ViewModels.Account;
using Osma.Mobile.App.ViewModels.Connections;
using Osma.Mobile.App.ViewModels.CreateInvitation;
using Osma.Mobile.App.ViewModels.Credentials;
using ReactiveUI;

namespace Osma.Mobile.App.ViewModels
{
    public class MainViewModel : ABaseViewModel
    {
        public MainViewModel(
            IUserDialogs userDialogs,
            INavigationService navigationService,
            LoginViewModel loginViewModel,
            ConnectionsViewModel connectionsViewModel,
            CredentialsViewModel credentialsViewModel,
            AccountViewModel accountViewModel,
            CreateInvitationViewModel createInvitationViewModel)
            : base(
                nameof(MainViewModel),
                userDialogs,
                navigationService
        )
        {
            Login = loginViewModel;
            Connections = connectionsViewModel;
            Credentials = credentialsViewModel;
            Account = accountViewModel;
            CreateInvitation = createInvitationViewModel;
        }

        public override async Task InitializeAsync(object navigationData)
        {
            await Login.InitializeAsync(null);
            await Connections.InitializeAsync(null);
            await Credentials.InitializeAsync(null);
            await Account.InitializeAsync(null);
            await CreateInvitation.InitializeAsync(null);
            await base.InitializeAsync(navigationData);
        }

        #region Bindable Properties
        private LoginViewModel _login;
        public LoginViewModel Login
        {
            get => _login;
            set => this.RaiseAndSetIfChanged(ref _login, value);
        }

        private ConnectionsViewModel _connections;
        public ConnectionsViewModel Connections
        {
            get => _connections;
            set => this.RaiseAndSetIfChanged(ref _connections, value);
        }

        private CredentialsViewModel _credentials;
        public CredentialsViewModel Credentials
        {
            get => _credentials;
            set => this.RaiseAndSetIfChanged(ref _credentials, value);
        }

        private AccountViewModel _account;
        public AccountViewModel Account
        {
            get => _account;
            set => this.RaiseAndSetIfChanged(ref _account, value);
        }

        private CreateInvitationViewModel _createInvitation;
        public CreateInvitationViewModel CreateInvitation
        {
            get => _createInvitation;
            set => this.RaiseAndSetIfChanged(ref _createInvitation, value);
        }
        #endregion
    }
}

1 Ответ

0 голосов
/ 13 апреля 2020

Я не вижу, чтобы у вас был экземпляр NavigationPage где-либо, так как работает ваш NavigationService?

NavigationService обычно вставляет страницу в стек страниц в экземпляре NaviagtionPage.

I видите, в App.xaml.cs вы делаете LoginPage своей главной страницей, но где вы переключаете ее на NavigationPage или на вашу вкладку?

Вам нужно проверить, какой должна быть ваша MainPage.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...