728x90
728x170

Login 페이지로 이전에 진행하려던 프로젝트를 안하게 되면서 남은 코드...(돈받고 했어야.. 씁;)


MauiProgram.cs

using Microsoft.Extensions.Logging;

namespace Maui.LoginSample;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

#if DEBUG
        builder.Logging.AddDebug();
#endif

#if ANDROID
        // Entry 에서 언더라인 제거
        Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("NoUnderline", (h, v) =>
        {
        
            h.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Transparent);
        });
#endif

        return builder.Build();
    }
}

Constants.cs

namespace Maui.LoginSample.Common
{
    public class Constants
    {
        public static string SaveIDKey = "SaveID";
        public static string SavePWKey = "SavePW";
    }
}

LoginInfo.cs

namespace Maui.LoginSample.Models
{
    public class LoginInfo
    {
        /// <summary>
        /// 로그인 아이디
        /// </summary>
        public string LoginId { get; set; }

        /// <summary>
        /// 로그인 패스워드
        /// </summary>
        public string LoginPw { get; set; }
    }
}

BaseViewModel.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Maui.LoginSample.ViewModels
{
    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string name = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public bool IsBusy
        {
            get { return isBusy; }
            set
            {
                isBusy = value;
                OnPropertyChanged();
            }
        }
        private bool isBusy;
    }
}

LoginPageModel.cs

using System.Windows.Input;

using Maui.LoginSample.Common;
using Maui.LoginSample.Models;
using Maui.LoginSample.Views;

namespace Maui.LoginSample.ViewModels
{
    public class LoginPageModel : BaseViewModel
    {
        #region Properties
        /// <summary>
        /// 현재 로그인한 사용자 정보입니다.
        /// </summary>
        public LoginInfo LoginInfo
        {
            get { return loginInfo; }
            set
            {
                loginInfo = value;
                OnPropertyChanged();
            }
        }
        private LoginInfo loginInfo;

        public bool IsSaveID
        {
            get { return isSaveID; }
            set
            {
                isSaveID = value;

                if (!value)
                {
                    Preferences.Remove(Constants.SaveIDKey);
                    IsSavePW = false;
                }

                OnPropertyChanged();
            }
        }
        private bool isSaveID = false;

        public bool IsSavePW
        {
            get { return isSavePW; }
            set
            {
                isSavePW = value;

                if (!value)
                {
                    Preferences.Remove(Constants.SavePWKey);
                }

                OnPropertyChanged();
            }
        }
        private bool isSavePW = false;
        #endregion

        #region Commands
        /// <summary>
        /// 로그인 Command 입니다.
        /// </summary>
        public ICommand LoginCommand => new Command(OnLogin);

        /// <summary>
        /// 아이디/패쓰워드 검색 Command 입니다. 
        /// </summary>
        public ICommand IdPwSearchCommand => new Command(OnIdPwSearch);

        /// <summary>
        /// 회원가입 Command 입니다.
        /// </summary>
        public ICommand MemberJoinCommand => new Command(OnMemberJoin);

        #endregion

        #region LoginPageModel
        public LoginPageModel()
        {
            this.LoginInfo = new LoginInfo();

            // 저장한 경우 처리
            if (Preferences.ContainsKey(Constants.SaveIDKey))
            {
                this.IsSaveID = true;
                this.LoginInfo.LoginId = Preferences.Get(Constants.SaveIDKey, "");
            }

            if (Preferences.ContainsKey(Constants.SavePWKey))
            {
                this.IsSavePW = true;
                this.LoginInfo.LoginPw = Preferences.Get(Constants.SavePWKey, "");
            }
        }
        #endregion

        // Methods
        #region OnLogin
        /// <summary>
        /// 로그인 메뉴를 나타냅니다.
        /// </summary>
        private async void OnLogin()
        {
            if (this.LoginInfo.LoginId == null)
            {
                await Application.Current.MainPage.DisplayAlert("ID 확인", "ID를 입력하세요", "OK");
                return;
            }

            if (this.LoginInfo.LoginPw == null)
            {
                await Application.Current.MainPage.DisplayAlert("비밀번호확인", "비밀번호를 입력하세요", "OK");

                return;
            }

            this.IsBusy = true;

            try
            {
                // 로그인 처리

                // 로그인 완료 시
                if (this.IsSaveID)
                {
                    Preferences.Remove(Constants.SaveIDKey);
                    Preferences.Set(Constants.SaveIDKey, LoginInfo.LoginId);
                }

                if (this.IsSavePW)
                {
                    Preferences.Remove(Constants.SavePWKey);
                    Preferences.Set(Constants.SavePWKey, LoginInfo.LoginPw);
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("에러", ex.Message, "OK");
                return;
            }
            finally
            {
                this.IsBusy = false;
            }

            App.Current.MainPage = new MainPage();
        }
        #endregion
        #region OnIdPwSearch
        private void OnIdPwSearch()
        {
            //Application.Current.MainPage.Navigation.PushAsync(new FindPage());
        }
        #endregion
        #region OnMemberJoin
        private async void OnMemberJoin()
        {
            //await Application.Current.MainPage.Navigation.PushAsync(new CreateUserPage());
        }
        #endregion
    }
}

LoginPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="Maui.LoginSample.Views.LoginPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:viewModels="clr-namespace:Maui.LoginSample.ViewModels">

    <ContentPage.BindingContext>
        <viewModels:LoginPageModel />
    </ContentPage.BindingContext>
    <Grid>
        <VerticalStackLayout>
            <Image
                x:Name="mainImage"
                Grid.Row="0"
                Margin="30,30"
                HeightRequest="200"
                HorizontalOptions="Center"
                Source="main.png" />

            <StackLayout
                Grid.Row="1"
                Margin="15"
                Orientation="Vertical"
                VerticalOptions="EndAndExpand">
                <Border
                    Margin="5"
                    BackgroundColor="White"
                    StrokeThickness="1">
                    <Border.StrokeShape>
                        <RoundRectangle CornerRadius="10, 10, 10, 10" />
                    </Border.StrokeShape>
                    <StackLayout Margin="30,20,30,20" Orientation="Vertical">
                        <Label
                            FontSize="14"
                            HorizontalOptions="Start"
                            Text="아이디"
                            TextColor="#024B89"
                            VerticalOptions="Center"
                            VerticalTextAlignment="Center" />
                        <StackLayout BackgroundColor="White" Orientation="Horizontal">
                            <Frame
                                Padding="5,0"
                                BackgroundColor="White"
                                BorderColor="Gray"
                                CornerRadius="3"
                                HasShadow="False"
                                HeightRequest="40"
                                HorizontalOptions="FillAndExpand">
                                <Entry
                                    x:Name="idEntry"
                                    BackgroundColor="White"
                                    FontSize="13"
                                    HorizontalOptions="FillAndExpand"
                                    Placeholder="아이디를 입력하세요"
                                    PlaceholderColor="LightGray"
                                    Text="{Binding LoginInfo.LoginId}"
                                    TextColor="Black"
                                    VerticalOptions="FillAndExpand" />
                            </Frame>
                        </StackLayout>
                        <BoxView
                            BackgroundColor="White"
                            HeightRequest="10"
                            Color="White" />
                        <Label
                            FontSize="14"
                            HorizontalOptions="Start"
                            Text="비밀번호"
                            TextColor="#024B89"
                            VerticalOptions="Center"
                            VerticalTextAlignment="Center" />

                        <StackLayout BackgroundColor="White" Orientation="Horizontal">
                            <Frame
                                Padding="5,0"
                                BackgroundColor="White"
                                BorderColor="Gray"
                                CornerRadius="3"
                                HasShadow="False"
                                HeightRequest="40"
                                HorizontalOptions="FillAndExpand">
                                <Entry
                                    x:Name="pwdEntry"
                                    BackgroundColor="White"
                                    FontSize="13"
                                    HorizontalOptions="FillAndExpand"
                                    IsPassword="True"
                                    Keyboard="Text"
                                    Placeholder="비밀번호"
                                    PlaceholderColor="LightGray"
                                    Text="{Binding LoginInfo.LoginPw}"
                                    TextColor="Black"
                                    VerticalOptions="FillAndExpand" />
                            </Frame>
                        </StackLayout>

                        <Grid Margin="5" ColumnDefinitions="3*,2*,3*,2*">
                            <Label
                                Grid.Column="0"
                                FontSize="12"
                                HorizontalTextAlignment="End"
                                Text="아이디 저장"
                                TextColor="Black"
                                VerticalOptions="Center" />
                            <Switch
                                Grid.Column="1"
                                IsToggled="{Binding IsSaveID}"
                                OnColor="Black"
                                ThumbColor="#054988" />
                            <Label
                                Grid.Column="2"
                                FontSize="12"
                                HorizontalTextAlignment="End"
                                Text="비밀번호 저장"
                                TextColor="Black"
                                VerticalOptions="Center" />
                            <Switch
                                Grid.Column="3"
                                IsToggled="{Binding IsSavePW}"
                                OnColor="Black"
                                ThumbColor="#054988" />

                        </Grid>

                        <StackLayout>
                            <Button
                                Margin="10"
                                BackgroundColor="#024B89"
                                Command="{Binding LoginCommand}"
                                CornerRadius="10"
                                HeightRequest="50"
                                Text="로그인"
                                TextColor="#ffffff">
                                <Button.FontSize>
                                    <OnPlatform x:TypeArguments="x:Double">
                                        <On Platform="iOS" Value="24" />
                                        <On Platform="Android" Value="20" />
                                    </OnPlatform>
                                </Button.FontSize>
                            </Button>
                        </StackLayout>

                        <Grid
                            Margin="0,0,0,0"
                            ColumnDefinitions="*,*"
                            VerticalOptions="Start">
                            <StackLayout Grid.Column="0">
                                <Button
                                    BackgroundColor="#ffffff"
                                    Command="{Binding IdPwSearchCommand}"
                                    CornerRadius="10"
                                    HeightRequest="50"
                                    Text="아이디/비번찿기"
                                    TextColor="Black">
                                    <Button.FontSize>
                                        <OnPlatform x:TypeArguments="x:Double">
                                            <On Platform="iOS" Value="18" />
                                            <On Platform="Android" Value="14" />
                                        </OnPlatform>
                                    </Button.FontSize>
                                </Button>
                            </StackLayout>
                            <StackLayout Grid.Column="1" HorizontalOptions="EndAndExpand">
                                <Button
                                    BackgroundColor="#ffffff"
                                    Command="{Binding MemberJoinCommand}"
                                    CornerRadius="10"
                                    HeightRequest="50"
                                    Text="회원가입"
                                    TextColor="Black">
                                    <Button.FontSize>
                                        <OnPlatform x:TypeArguments="x:Double">
                                            <On Platform="iOS" Value="18" />
                                            <On Platform="Android" Value="14" />
                                        </OnPlatform>
                                    </Button.FontSize>
                                </Button>
                            </StackLayout>
                        </Grid>
                    </StackLayout>
                </Border>
            </StackLayout>
        </VerticalStackLayout>
        <ActivityIndicator
            IsRunning="True"
            IsVisible="{Binding IsBusy}"
            WidthRequest="60"
            Color="Gray" />
    </Grid>

</ContentPage>


결과


[Source]

https://github.com/kei-soft/Maui.LoginSample

 

GitHub - kei-soft/Maui.LoginSample: Simple Login Page

Simple Login Page. Contribute to kei-soft/Maui.LoginSample development by creating an account on GitHub.

github.com

 

728x90
그리드형

'C# > Xamarin Maui' 카테고리의 다른 글

[.NET MAUI] Google reCAPTCHA  (0) 2023.04.12
[.NET MAUI] Share  (0) 2023.04.12
[.NET MAUI] NavigationPage Bar color 변경하기  (0) 2023.03.23
figma to maui graphics  (0) 2023.03.22
[.NET MAUI] 디바이스 기능 알아보기  (0) 2023.03.21
Posted by kjun
,