Проверка регистрации и входа в систему с помощью приложения.Текущий.Свойства в формах Xamarin

#c# #xaml #xamarin #xamarin.forms

#c# #xaml #xamarin #xamarin.forms

Вопрос:

У меня есть страница регистрации. Сначала пользователь вводит свои данные, такие как адрес электронной почты, пароль, вес, рост… После того, как пользователь заполнил эту форму, я хочу сохранить наиболее важную информацию, адрес электронной почты и пароль. Затем я хочу использовать эти данные на странице входа (в моем случае с именем на главной странице). Поэтому мне нужно сохранить, а затем проверить эту информацию на странице входа, какой пользователь вводит true или false

Я добавляю свою страницу регистрации и другой код. Если у вас есть какие-либо идеи или предложения, я открыт для них.

     <?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="HealNow.Signup"
             NavigationPage.HasNavigationBar="False">
    <ContentPage.Resources>
        <ResourceDictionary>
            <LinearGradientBrush x:Key="Theme" EndPoint="0,1">
                <GradientStop Color="#48b6a6" Offset="0.1" />
                <GradientStop Color="#2b78d4" Offset="1.0" />
            </LinearGradientBrush>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Padding>
        <OnPlatform x:TypeArguments="Thickness" iOS="0, 20, 0, 0">
        </OnPlatform>
    </ContentPage.Padding>
    <StackLayout Background="{StaticResource Theme}">
        <StackLayout Background="{StaticResource Theme}" >
        </StackLayout>
        <StackLayout Margin="0,35,0,0">
            <Image HorizontalOptions="Center"    HeightRequest="60" WidthRequest="60" Source="heartbeatt.png" ></Image>
        </StackLayout>
        <StackLayout Padding="0" Margin="10,20,10,0" HorizontalOptions="FillAndExpand" >
            <Frame BackgroundColor="Transparent" HeightRequest="600" Padding="0" Margin="0">
                <StackLayout>


                    <StackLayout Padding="0" Margin="15,10">

                        <Frame BackgroundColor="Transparent" BorderColor="White" Padding="0" HorizontalOptions="FillAndExpand" CornerRadius="30">
                            <StackLayout Orientation="Horizontal">
                                <Frame BackgroundColor="Transparent" HeightRequest="40" WidthRequest="40" CornerRadius="30" Padding="0" Margin="5">
                                    <Image Source="user.png" Aspect="AspectFill" Margin="0"/>
                                </Frame>
                                <Entry x:Name ="email" Placeholder="Email" TextColor="#666666" FontAttributes="None" HorizontalOptions="FillAndExpand" Margin="0,0,20,0" Completed="OnChange"/>
                            </StackLayout>
                        </Frame>

                        <Frame BackgroundColor="Transparent" BorderColor="White" Margin="0,12,0,0" Padding="0" HorizontalOptions="FillAndExpand" CornerRadius="30">
                            <StackLayout Orientation="Horizontal">
                                <Frame BackgroundColor="Transparent" HeightRequest="40" WidthRequest="40" CornerRadius="30" Padding="0" Margin="5">
                                    <Image Source="broken.png" Aspect="AspectFill" Margin="0"/>
                                </Frame>
                                <Entry x:Name ="password" Placeholder="Password" IsPassword="True" TextColor="White" FontAttributes="None" HorizontalOptions="FillAndExpand" Margin="0,0,20,0" Completed="OnChange"/>
                            </StackLayout>
                        </Frame>


                        <Frame BackgroundColor="Transparent" BorderColor="White" Margin="0,12,0,0" Padding="0" HorizontalOptions="FillAndExpand" CornerRadius="30">
                            <StackLayout Orientation="Horizontal">
                                <Frame BackgroundColor="Transparent" HeightRequest="40" WidthRequest="40" CornerRadius="30" Padding="0" Margin="5">
                                    <Image Source="babyy.png" Aspect="AspectFill"  Margin="0"/>
                                </Frame>
                                <Entry Placeholder="Date of Birth"  TextColor="White" FontAttributes="None" HorizontalOptions="FillAndExpand" Margin="0,0,20,0"/>
                            </StackLayout>
                        </Frame>

                        <Frame BackgroundColor="Transparent" Margin="0,12,0,0" BorderColor="White" Padding="0" HorizontalOptions="FillAndExpand" CornerRadius="30">
                            <StackLayout Orientation="Horizontal">
                                <Frame BackgroundColor="Transparent" HeightRequest="40" WidthRequest="40" CornerRadius="30" Padding="0" Margin="5">
                                    <Image Source="barrr.png" Aspect="AspectFill" Margin="0"/>
                                </Frame>
                                <Entry Placeholder="Weight" TextColor="#666666" FontAttributes="None" HorizontalOptions="FillAndExpand" Margin="0,0,20,0"/>
                            </StackLayout>
                        </Frame>

                        <Frame BackgroundColor="Transparent" Margin="0,12,0,0" BorderColor="White" Padding="0" HorizontalOptions="FillAndExpand" CornerRadius="30">
                            <StackLayout Orientation="Horizontal">
                                <Frame BackgroundColor="Transparent" HeightRequest="40" WidthRequest="40" CornerRadius="30" Padding="0" Margin="5">
                                    <Image Source="height.png" Aspect="AspectFill" Margin="0"/>
                                </Frame>
                                <Entry Placeholder="Height" TextColor="#666666" FontAttributes="None" HorizontalOptions="FillAndExpand" Margin="0,0,20,0"/>
                            </StackLayout>
                        </Frame>



                        <Button Margin="30" Text="SIGN UP" BackgroundColor="#2a52be" TextColor="White" CornerRadius="30" Clicked="Button_Clicked" />


                       

                        

                </StackLayout>
        </StackLayout>
            </Frame>
            
        </StackLayout>
        </StackLayout>
</ContentPage>
 

и это выглядит так

Регистрация.xaml.cs

     using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

namespace HealNow
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Signup : ContentPage
    {
        public Signup()
        {
            InitializeComponent();
            Application.Current.Properties[email.Text] = password.Text;
            if (Application.Current.Properties.ContainsKey("Email"))
            {
                var email = Application.Current.Properties["Email"] as string;

            }
            if (Application.Current.Properties.ContainsKey("Password"))
            {
                var password = Application.Current.Properties["Password"] as string;

            }
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new MainPage());
        }

        private void OnChange(object sender, EventArgs e)
        {
            Application.Current.Properties["Email"] = email.Text;
            Application.Current.Properties["Password"] = password.Text;

            Application.Current.SavePropertiesAsync();
        }
        protected override void OnDisappearing()
        {
            base.OnDisappearing();
        }

    }
}
 

MainPage.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="HealNow.MainPage"
             NavigationPage.HasNavigationBar="False">
    <ContentPage.Padding>
        <OnPlatform x:TypeArguments="Thickness" iOS="0, 20, 0, 0">
        </OnPlatform>
    </ContentPage.Padding>
    <StackLayout>
        <StackLayout.Background>
            <LinearGradientBrush x:Name="Theme" EndPoint="0,1">
                <GradientStop Color="#48b6a6" Offset="0.1" />
                <GradientStop Color="#2b78d4" Offset="1.0" />
            </LinearGradientBrush>
        </StackLayout.Background>
        <StackLayout Margin="0,35,0,0">
            <Image HorizontalOptions="Center"    HeightRequest="60" WidthRequest="60" Source="heartbeatt.png" ></Image>
        </StackLayout>
        <StackLayout Padding="0" Margin="10,20,10,0" HorizontalOptions="FillAndExpand" >
            <Frame BackgroundColor="Transparent" HeightRequest="600" Padding="0" Margin="0">
                <StackLayout>

                    <StackLayout Padding="0" Margin="15,10">

                        <Frame BackgroundColor="Transparent" BorderColor="White" Padding="0" HorizontalOptions="FillAndExpand" CornerRadius="30">
                            <StackLayout Orientation="Horizontal">
                                <Frame BackgroundColor="Transparent" HeightRequest="40" WidthRequest="40" CornerRadius="30" Padding="0" Margin="5">
                                    <Image Source="user.png" Aspect="AspectFill" Margin="0"/>
                                </Frame>
                                <Entry x:Name="email2"  Placeholder="Email" TextColor="#666666" FontAttributes="None" HorizontalOptions="FillAndExpand" Margin="0,0,20,0"/>
                            </StackLayout>
                        </Frame>

                        <Frame BackgroundColor="Transparent" BorderColor="White" Margin="0,15,0,0" Padding="0" HorizontalOptions="FillAndExpand" CornerRadius="30">
                            <StackLayout Orientation="Horizontal">
                                <Frame BackgroundColor="Transparent" HeightRequest="40" WidthRequest="40" CornerRadius="30" Padding="0" Margin="5">
                                    <Image Source="broken.png" Aspect="AspectFill" Margin="0"/>
                                </Frame>
                                <Entry x:Name="password2" Placeholder="Password" IsPassword="True" TextColor="White" FontAttributes="None" HorizontalOptions="FillAndExpand" Margin="0,0,20,0"/>
                            </StackLayout>
                        </Frame>

                        <StackLayout  Orientation="Horizontal">
                            <CheckBox IsChecked="False" Color="White" />
                            <Label Text="Remember me" TextColor="White" FontSize="10" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" />

                            <Label Text="Forgot Password" TextColor="White"  HorizontalOptions="EndAndExpand" FontSize="10" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" />
                        </StackLayout>

                        <Button Margin="10" Text="SIGN IN" BackgroundColor="#2b78d4" TextColor="White" CornerRadius="30" Clicked="Button_Clicked" />
                        <StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
                            <Label Text="Still Not Connected ?" TextColor="White" FontSize="10"/>
                            <Button Margin="0,-17,0,0" Text="Sign Up" TextColor="White" FontAttributes="Bold" FontSize="10" BackgroundColor="Transparent" Clicked="Button_Clicked2" />

                        </StackLayout>

                        <StackLayout Margin="0,25,0,0" Padding="0">
                            <Grid>
                                <BoxView BackgroundColor="White" HeightRequest="1" WidthRequest="150"  HorizontalOptions="Center" VerticalOptions="Center"/>
                                <Frame BackgroundColor="White" HeightRequest="45" WidthRequest="45" CornerRadius="45" HasShadow="False" BorderColor="White" Margin="0" HorizontalOptions="Center" Padding="0">
                                    <Label Text="OR" TextColor="#666666" FontSize="Small" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
                                </Frame>
                            </Grid>
                        </StackLayout>

                        <StackLayout Margin="0,25" Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
                            <Frame BackgroundColor="Transparent" HeightRequest="45" WidthRequest="45" CornerRadius="45" HasShadow="False" BorderColor="White" Margin="0" HorizontalOptions="Center" Padding="0">
                                <Image Source="https://www.pngitem.com/pimgs/m/44-440455_transparent-background-fb-logo-hd-png-download.png" Aspect="AspectFill" Margin="0"/>
                            </Frame>
                            <Frame BackgroundColor="Transparent" HeightRequest="45" WidthRequest="45" CornerRadius="45" HasShadow="False" BorderColor="White" Margin="0" HorizontalOptions="Center" Padding="0">
                                <Image Source="https://blog.hubspot.com/hubfs/image8-2.jpg" Aspect="AspectFill" Margin="0"/>
                            </Frame>
                        </StackLayout>

                    </StackLayout>
                </StackLayout>
            </Frame >
        </StackLayout>
    </StackLayout >
</ContentPage>
 

MainPage.xaml.cs

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace HealNow
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private async void Button_Clicked(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new WelcomePage());
        }
        private async void Button_Clicked2(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new Signup());
        }
    }
}
 

Комментарии:

1. в чем ваш вопрос? Вы рассказали нам, что вы хотите сделать, и опубликовали МНОГО кода, но вы не задали вопрос. Что-то не так с вашим кодом? Выдает ли if ошибку или исключение, или это просто работает не так, как вы хотите?

2. Ну, моя проблема в том, как проверить комбинацию электронной почты и пароля на главной странице (которую я сохранил на странице регистрации со словарем свойств). Я ищу что-то вроде if( Application. Текущий. Свойства [email.Text] = email2.Text;) перейдите на страницу приветствия или отобразите всплывающую ошибку.

3. Итак, я имею в виду, что я могу просто взять адрес электронной почты и пароль (они являются переменными страницы регистрации), а затем использовать его для email2 и password2 (которые находятся на главной странице), сравнить их равными или нет? Я оспариваю синтаксис @Cfun

4. то, что вы упомянули ( if( Application.Current.Properties[email.Text] == email2.Text) ), не работает? ‘double «=» и без «;» в конце.

5. @Cfun но они находятся на разных страницах (регистрация и главная страница). Так будут ли проблемы с доступом?

Ответ №1:

 string email;
string password;

public MainPage()
{
  InitializeComponent();

  if (Application.Current.Properties.ContainsKey("Email"))
  {
     email = Application.Current.Properties["Email"] as string;
  }
  if (Application.Current.Properties.ContainsKey("Password"))
  {
     password = Application.Current.Properties["Password"] as string;
  }
}
 

Комментарии:

1. Итак, я должен просто удалить x:Name= email2 и x:Name= password2 на главной странице и заменить их электронной почтой и паролем?

2. и я записал ваш код также на странице регистрации, так что я должен его удалить? или этот код должен оставаться обоими расширениями .cs?