WPF实战学习笔记29-登录数据绑定,编写登录服务

添加登录绑定字段、命令、方法

修改对象:Mytodo.ViewModels.ViewModels

c# 复制代码
using Mytodo.Service;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;

namespace Mytodo.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {


        #region 定义命令
        /// <summary>
        /// 执行登录|推出等相关命令
        /// </summary>
        public DelegateCommand<string> ExecuteCommand { get; set; }
        #endregion

        #region 定义属性

        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        public string Account
        {
            get { return account; }
            set { account = value; }
        }

        #endregion

        #region 定义重要字段

        #endregion

        #region 定义普通字段
        private string password;
        private string account;
        private readonly ILoginService loginService;
        private readonly IEventAggregator aggregator;
        #endregion

        #region 命令方法
        /// <summary>
        /// ExecuteCommand对应的方法
        /// </summary>
        /// <param name="obj"></param>
        private void Execute(string obj)
        {
            switch (obj)
            {
                case "Login": Login(); break;
                case "LoginOut": LoginOut(); break;
                //case "Resgiter": Resgiter(); break;
                //case "ResgiterPage": SelectIndex = 1; break;
                //case "Return": SelectIndex = 0; break;
            }
        }

        private void LoginOut()
        {
            //if (string.IsNullOrWhiteSpace(UserName) ||
            //   string.IsNullOrWhiteSpace(PassWord))
            //{
            //    return;
            //}

            //var loginResult = await LoginService.Login(new Shared.Dtos.UserDto()
            //{
            //    Account = UserName,
            //    PassWord = PassWord
            //});

            //if (loginResult != null && loginResult.Status)
            //{
            //    RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            //}
            //else
            //{
            //    //登录失败提示...
            //    aggregator.SendMessage(loginResult.Message, "Login");
            //}
        }

        private void Login()
        {
            //throw new NotImplementedException();
        }

        #endregion

        #region 启动项

        #endregion

        #region 继承
        public string Title { get; set; } = "Todo";


        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            LoginOut();
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }
        #endregion

        public LoginViewModel(ILoginService loginService, IEventAggregator aggregator)
        {
            ExecuteCommand = new DelegateCommand<string> (Execute);
            this.loginService = loginService;
            this.aggregator = aggregator;
        }

  
    }
}

添加密码依赖对象行为

添加文件:Mytodo.Extensions.PassWordExtensions

c# 复制代码
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Mytodo.Extensions
{
    public class PassWordExtensions
    {
        public static string GetPassWord(DependencyObject obj)
        {
            return (string)obj.GetValue(PassWordProperty);
        }

        public static void SetPassWord(DependencyObject obj, string value)
        {
            obj.SetValue(PassWordProperty, value);
        }

        // Using a DependencyProperty as the backing store for PassWord.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PassWordProperty =
            DependencyProperty.RegisterAttached("PassWord", typeof(string), typeof(PassWordExtensions), new FrameworkPropertyMetadata(string.Empty, OnPassWordPropertyChanged));

        private static void OnPassWordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var passWord = d as PasswordBox;
            string password = (string)e.NewValue;

            if (passWord != null && passWord.Password != password)
                passWord.Password = password;
        }

    }

    public class PasswordBehavior : Behavior<PasswordBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.PasswordChanged += AssociatedObject_PasswordChanged;
        }

        private void AssociatedObject_PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            string password = PassWordExtensions.GetPassWord(passwordBox);

            if (passwordBox != null && passwordBox.Password != password)
                PassWordExtensions.SetPassWord(passwordBox, passwordBox.Password);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.PasswordChanged -= AssociatedObject_PasswordChanged;
        }
    }
}

### 登录UI添加密码行为

修改文件:Mytodo.Views.LoginView.xmal

  1. 添加命名空间,略
  2. 修改passbox。
xaml 复制代码
<PasswordBox
             Margin="0,10"
             md:HintAssist.Hint="请输入密码"
             pass:PassWordExtensions.PassWord="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             DockPanel.Dock="Top">
    <i:Interaction.Behaviors>
        <pass:PasswordBehavior />
    </i:Interaction.Behaviors>
</PasswordBox>

添加加密方法,并使用

添加文件:MyToDo.Share.StringExtensions.cs

c# 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.Share
{
    public static class StringExtensions
    {
        public static string GetMD5(this string data)
        {
            if (string.IsNullOrWhiteSpace(data))
                throw new ArgumentNullException(nameof(data));

            var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(data));

            return Convert.ToBase64String(hash);//将加密后的字节数组转换为加密字符串
        }
    }
}

客户端添加登录和注册接口

添加文件:Mytodo.Service.cs

c# 复制代码
using MyToDo.Share.Models;
using MyToDo.Share;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.Service
{
    public interface ILoginService
    {
        Task<ApiResponse> Login(UserDto user);

        Task<ApiResponse> Resgiter(UserDto user);
    }
}

添加文件:Mytodo.Service.LoginService

c# 复制代码
using MyToDo.Share;
using MyToDo.Share.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.Service
{
    public class LoginService : ILoginService
    {
        private readonly HttpRestClient client;
        private readonly string serviceName = "Login";

        public LoginService(HttpRestClient client)
        {
            this.client = client;
        }

        public async Task<ApiResponse> Login(UserDto user)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.POST;
            request.Route = $"api/{serviceName}/Login";
            request.Parameter = user;
            return await client.ExecuteAsync(request);
        }

        public async Task<ApiResponse> Resgiter(UserDto user)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.POST;
            request.Route = $"api/{serviceName}/Resgiter";
            request.Parameter = user;
            return await client.ExecuteAsync(request);
        }
    }
}

注册接口和服务

Mytodo.app.xaml.cs 添加内容containerRegistry.Register<ILoginService, LoginService>();

相关推荐
红中马喽14 分钟前
JS学习日记(webAPI—DOM)
开发语言·前端·javascript·笔记·vscode·学习
尘浮生2 小时前
Java项目实战II基于微信小程序的移动学习平台的设计与实现(开发文档+数据库+源码)
java·开发语言·数据库·spring boot·学习·微信小程序·小程序
huangkj-henan2 小时前
DA217应用笔记
笔记
Young_202202022 小时前
学习笔记——KMP
笔记·学习
行然梦实3 小时前
学习日记_20241110_聚类方法(K-Means)
学习·kmeans·聚类
马船长3 小时前
制作图片木马
学习
秀儿还能再秀3 小时前
机器学习——简单线性回归、逻辑回归
笔记·python·学习·机器学习
WCF向光而行3 小时前
Getting accurate time estimates from your tea(从您的团队获得准确的时间估计)
笔记·学习
wang09073 小时前
工作和学习遇到的技术问题
学习
Li_0304065 小时前
Java第十四天(实训学习整理资料(十三)Java网络编程)
java·网络·笔记·学习·计算机网络