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

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

修改对象:Mytodo.ViewModels.ViewModels

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 定义命令
        /// 
        /// 执行登录|推出等相关命令
        /// 
        public DelegateCommand 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 命令方法
        /// 
        /// ExecuteCommand对应的方法
        /// 
        /// 
        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 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 (Execute);
            this.loginService = loginService;
            this.aggregator = aggregator;
        }

  
    }
}

添加密码依赖对象行为

添加文件:Mytodo.Extensions.PassWordExtensions

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
    {
        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。

    
        
    

添加加密方法,并使用

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

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

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 Login(UserDto user);

        Task Resgiter(UserDto user);
    }
}

添加文件:Mytodo.Service.LoginService

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 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 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();

你可能感兴趣的:(WPF实战学习笔记,wpf,学习,笔记)