WPF实战学习笔记32-登录、注册服务添加

增加全局账户名同步

增加静态变量

添加文件:Mytodo.Common.Models.AppSession.cs

ausing Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;namespace Mytodo.Common.Models
{public class AppSession{private static String userName;/// <summary>/// A static property which you'd like to bind to/// </summary>public static String UserName{get{return userName;}set{userName = value;// Raise a change eventOnUserNameChanged(EventArgs.Empty);}}// Declare a static event representing changes to your static propertypublic static event EventHandler UserNameChanged;// Raise the change event through this static methodprotected static void OnUserNameChanged(EventArgs e){EventHandler handler = UserNameChanged;if (handler != null){handler(null, e);}}static AppSession(){// Set up an empty event handlerUserNameChanged += (sender, e) => { return; };}}
}

修改MainView绑定

  1. 增加命名空间
xmlns:model="clr-namespace:Mytodo.Common.Models"
  1. 修改textblock绑定
<TextBlockMargin="0,10"HorizontalAlignment="Center"Text="{Binding Path=(model:AppSession.UserName)}" />

给账户名赋值

修改Mytodo.ViewModels.LoginViewModel.cs

async private void Login()
{if (string.IsNullOrWhiteSpace(Account) ||string.IsNullOrWhiteSpace(Password)){aggregator.SendMessage("密码或账户为空,请重新输入", "Login");return;}var loginResult = await loginService.Login(new UserDto(){Account = Account,PassWord = Password});if (loginResult != null && loginResult.Status){//UserDto myuser= new UserDto() { UserName=loginResult.Result }// AppSession.UserNameAppSession.UserName = (loginResult.Result as UserDto).UserName;RequestClose?.Invoke(new DialogResult(ButtonResult.OK));return;}else{//登录失败提示...aggregator.SendMessage("密码或账户错误,请重新输入", "Login");}
}

添加注销功能

添加注销方法

修改文件:Mytodo.app.xaml.cs

public static void LoginOut(IContainerProvider containerProvider)
{Current.MainWindow.Hide();var dialog = containerProvider.Resolve<IDialogService>();dialog.ShowDialog("LoginView", callback =>{if (callback.Result != ButtonResult.OK){Environment.Exit(0);return;}Current.MainWindow.Show();});
}

添加注销命令,并初始化

修改文件:Mytodo.ViewModels.MainViewModel.cs

using Mytodo.Common;
using Mytodo.Common.Models;
using Mytodo.Extensions;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;namespace Mytodo.ViewModels
{public class MainViewModel : BindableBase, IConfigureInterface{public MainViewModel(IRegionManager regm, IContainerProvider provider){MenuBars = new ObservableCollection<MenuBar>();//区域赋值this.regionManager = regm;this.provider = provider;//初始化命令操作NavigateCmd = new DelegateCommand<MenuBar>(Navigate);LoginOutCommand = new DelegateCommand(Logout);//实例化命令GoBackCmd = new DelegateCommand(() =>{if (journal != null && journal.CanGoBack)journal.GoBack();});GoFwrdCmd = new DelegateCommand(() =>{if (journal != null && journal.CanGoForward)journal.GoForward();});}private void Logout(){App.LoginOut(provider);}//添加变量private readonly IRegionManager regionManager;private readonly IContainerProvider provider;private IRegionNavigationJournal journal;//添加命令public DelegateCommand LoginOutCommand { get; set; }public DelegateCommand<MenuBar> NavigateCmd { get; private set; }/// <summary>/// 导航返回命令/// </summary>public DelegateCommand GoBackCmd { get; private set; }/// <summary>/// 导航前进命令/// </summary>public DelegateCommand GoFwrdCmd { get; private set; }//命令方法private void Navigate(MenuBar obj){if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))return;regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(obj.NameSpace, back =>{journal = back.Context.NavigationService.Journal;});}private ObservableCollection<MenuBar> menuBars;public ObservableCollection<MenuBar> MenuBars{get { return menuBars; }set { menuBars = value; RaisePropertyChanged(); }}void CreatMenuBar(){MenuBars.Add(new MenuBar { Icon = "Home", NameSpace = "IndexView", Title = "首页" });MenuBars.Add(new MenuBar { Icon = "FormatListChecks", NameSpace = "TodoView", Title = "待办事项" });MenuBars.Add(new MenuBar { Icon = "Notebook", NameSpace = "MemoView", Title = "备忘录" });MenuBars.Add(new MenuBar { Icon = "Cog", NameSpace = "SettingsView", Title = "设置" });}public void Configure(){CreatMenuBar();//导航到主页regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("IndexView");}}
}

修改xaml,增加注销按钮

<materialDesign:PopupBox Panel.ZIndex="1"><materialDesign:PopupBox.ToggleContent><ImageWidth="50"Height="50"Margin="16,0,0,0"Source="../Images/user.jpg"><Image.Clip><EllipseGeometryCenter="25,25"RadiusX="25"RadiusY="25" /></Image.Clip></Image></materialDesign:PopupBox.ToggleContent><StackPanel><!--<Button Command="{Binding AppCenterCommand}" Content="个人中心"/>--><Button Command="{Binding LoginOutCommand}" Content="注销当前账户" /></StackPanel>
</materialDesign:PopupBox>

首页添加用户名和时间

修改文件:Mytodo.ViewModels.IndexViewModel.cs

public DateTime CurrTime
{get { return currTime; }set { currTime = value; RaisePropertyChanged(); }
}
private string title;public string Title
{get { return title; }set { title = value; RaisePropertyChanged(); }
}
private DateTime currTime;
private async void RefreshTimeAsync()
{while (true){await Task.Delay(1000);CurrTime = DateTime.Now;Title = "您好 " + AppSession.UserName + ", 现在是: " + currTime.ToString("yy-MM-dd") + " " + currTime.ToString("HH:MM:ss") + " " + currTime.ToString("ddd");}
}
public IndexViewModel(IContainerProvider provider,IDialogHostService dialog) : base(provider)
{//实例化接口this.toDoService = provider.Resolve<ITodoService>();this.memoService = provider.Resolve<IMemoService>();this.summService = provider.Resolve<ISummeryService>();this.regionManager = provider.Resolve<IRegionManager>();//初始化命令EditMemoCmd = new DelegateCommand<MemoDto>(Addmemo);EditTodoCmd = new DelegateCommand<ToDoDto>(Addtodo);ToDoCompltedCommand = new DelegateCommand<ToDoDto>(Compete);ExecuteCommand = new DelegateCommand<string>(Execute);NavigateCommand = new DelegateCommand<TaskBar>(Navigate);this.dialog = dialog;CreatBars();RefreshTimeAsync();
}

修改bug

修改服务接口

修改ExecuteAsync()函数,修改HttpRestClient文件

using Newtonsoft.Json;
using RestSharp;
using RestSharp.Extensions;
using RestSharp.Serializers;
using RestSharp.Authenticators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyToDo.Share;
using MyToDo.Share.Models;
using Microsoft.AspNetCore.Http;namespace Mytodo.Service
{/// <summary>/// Http本地客户端/// </summary>public class HttpRestClient{private readonly string? apiUrl;protected readonly RestClient? client;public HttpRestClient(string apiUrl){this.apiUrl = apiUrl;client = new RestClient();}/// <summary>/// 异步执行/// </summary>/// <param name="baseRequest"></param>/// <returns></returns>public async Task<ApiResponse> ExecuteAsync(BaseRequest baseRequest){var request = new RestRequest(baseRequest.Method);request.AddHeader("Content-Type", baseRequest.ContentType);if (baseRequest.Parameter != null)request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);client.BaseUrl = new Uri(apiUrl + baseRequest.Route);var response = await client.ExecuteAsync(request);var apires = JsonConvert.DeserializeObject<ApiResponse>(response.Content);if (apires.Status){///return JsonConvert.DeserializeObject<ApiResponse>(response.Content);return new ApiResponse(){Status = true,Result = JsonConvert.DeserializeObject<UserDto>(apires.Result.ToString()),Message = ""};}   elsereturn new ApiResponse(){Status = false,Result = null,Message = response.ErrorMessage};}public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest){var request = new RestRequest(baseRequest.Method);request.AddHeader("Content-Type", baseRequest.ContentType);if (baseRequest.Parameter != null)request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);client.BaseUrl = new Uri(apiUrl + baseRequest.Route);var response = await client.ExecuteAsync(request);if (response.StatusCode == System.Net.HttpStatusCode.OK)return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content);elsereturn new ApiResponse<T>(){Status = false,Message = response.ErrorMessage};}}
}

调换注册界面数据绑定

<TextBoxMargin="0,5"md:HintAssist.Hint="请输入用户名"DockPanel.Dock="Top"Text="{Binding RUserDto.UserName}" />
<TextBoxMargin="0,5"md:HintAssist.Hint="请输入账号"DockPanel.Dock="Top"Text="{Binding RUserDto.Account}" />

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/15570.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

(树) 剑指 Offer 27. 二叉树的镜像 ——【Leetcode每日一题】

❓剑指 Offer 27. 二叉树的镜像 难度&#xff1a;简单 请完成一个函数&#xff0c;输入一个二叉树&#xff0c;该函数输出它的镜像。 例如输入&#xff1a; 4/ \2 7/ \ / \1 3 6 9镜像输出&#xff1a; 4/ \7 2/ \ / \9 6 3 1示例 1&#xff1a; 输…

28_计算机网络(Computer Networks)基础

本篇介绍计算机网络的基础知识。 文章目录 1. 计算机网络历史2. 以太网" (Ethernet)2.1 以太网" (Ethernet)的简单形式及概念2.2 指数退避解决冲突问题2.3 利用交换机减少同一载体中设备2.4 互联网&#xff08;The Internet&#xff09;2.5 路由(routing)2.6 数据包…

基于峰谷分时电价引导下的电动汽车充电负荷优化(matlab代码)

目录 1 主要内容 峰谷电价优化 电动汽车充电负荷变化 2 部分代码 3 程序结果 1 主要内容 该程序基本复现《基于峰谷分时电价引导下的电动汽车充电负荷优化》&#xff0c;代码主要做的是基于NSGA-II的电动汽车充电负荷优化&#xff0c;首先&#xff0c;在研究电动汽车用户充…

重生之我要学C++第五天

这篇文章主要内容是构造函数的初始化列表以及运算符重载在顺序表中的简单应用&#xff0c;运算符重载实现自定义类型的流插入流提取。希望对大家有所帮助&#xff0c;点赞收藏评论&#xff0c;支持一下吧&#xff01; 目录 构造函数进阶理解 1.内置类型成员在参数列表中的定义 …

Webpack5 多线程Threads

文章目录 一、Threads 是什么&#xff1f;二、为什么使用 Threads&#xff1f;三、怎么使用 Threads&#xff1f;注意事项结论 一、Threads 是什么&#xff1f; Threads 是指在计算机领域中&#xff0c;指的是操作系统分配给处理器执行任务的最小单位。在Webpack5中&#xff0…

【Matlab】基于BP神经网络的数据回归预测新数据(Excel可直接替换数据)

【Matlab】基于BP神经网络的数据回归预测新数据(Excel可直接替换数据) 1.模型原理2.数学公式3.文件结构4.Excel数据5.分块代码5.1 main.m5.2 NewData.m6.完整代码6.1 main.m6.2 NewData.m7.运行结果1.模型原理 基于BP神经网络的数据回归预测是一种常见的机器学习方法,用于处…

【云原生】Docker容器命令监控+Prometheus监控平台

目录 1.常用命令监控 docker ps docker top docker stats 2.weave scope 1.下载 2.安装 3.访问查询即可 3.Prometheus监控平台 1.部署数据收集器cadvisor 2.部署Prometheus 3.部署可视化平台Gragana 4.进入后台控制台 1.常用命令监控 docker ps [rootlocalhost ~…

重新审视MHA与Transformer

本文将基于PyTorch源码重新审视MultiheadAttention与Transformer。事实上&#xff0c;早在一年前博主就已经分别介绍了两者&#xff1a;各种注意力机制的PyTorch实现、从零开始手写一个Transformer&#xff0c;但当时的实现大部分是基于d2l教程的&#xff0c;这次将基于PyTorch…

opencv顺时针,逆时针旋转视频并保存视频

原视频 代码 import cv2# 打开视频文件 video cv2.VideoCapture(inference/video/lianzhang.mp4)# 获取原视频的宽度和高度 width int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) height int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))# 创建视频编写器并设置输出视频参数 fourcc …

YAML+PyYAML笔记 4 | YAML字符流、节点属性、块伸缩标头使用

4 | YAML字符流、节点属性、块伸缩标头使用 1 字符流1.1 表示方式1.2 字符流解析 2 节点属性3 块伸缩标头 1 字符流 1.1 表示方式 YAML字符流是将多个文档放在同一个文件中&#xff0c;通过“—”分隔符进行分割&#xff1b;示例&#xff1a; --- user1:name: xiaomingage: …

【C++】类和对象(下)

1、初始化列表 初始化列表&#xff1a;以一个冒号开始&#xff0c;接着是一个以逗号分隔的数据成员列表&#xff0c;每个"成员变量"后面跟一个放在括号中的初始值或表达式。 class Date { public:Date(int year, int month, int day): _year(year), _month(month), _…

OSPF协议RIP协议+OSPF实验(eNSP)

本篇博客主要讲解单区域的ospf&#xff0c;多区域的仅作了解。 目录 一、OSPF路由协议概述 1.内部网关协议和外部网关协议 二、OSPF的应用环境 1.从以下几方面考虑OSPF的使用 2.OSPF的特点 三、OSPF重要基本概念 3.1&#xff0c;辨析邻居和邻接关系以及七种邻居状态 3…

【MySQL】索引与B+树

【MySQL】索引与B树 索引概念前导硬件软件方面 索引的理解单个page多个page引入B树B树的特征为什么B树做索引优于其他数据结构&#xff1f;聚簇索引与非聚簇索引辅助索引 索引的创建主键索引的创建和查看唯一键索引的创建和查看普通索引的创建和查看复合索引全文索引索引的其他…

js全端支持的深拷贝structuredClone

Jul 7, 2023 经过一年半的试用&#xff0c;structuredClone转正了&#xff0c;全端可以正式使用。 https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

Rust- 错误处理

Rust approaches error handling with the aim of being explicit about possible error conditions. It separates the concerns of “normal” return values and “error” return values by using a specific set of types for each concern. Rust’s primary tools for ex…

OpenHarmony开源鸿蒙学习入门 - 基于3.2Release 应用开发环境安装

OpenHarmony开源鸿蒙学习入门 - 基于3.2Release 应用开发环境安装 基于目前官方master主支&#xff0c;最新文档版本3.2Release&#xff0c;更新应用开发环境安装文档。 一、安装IDE&#xff1a; 1.IDE安装的系统要求 2.IDE下载官网链接&#xff08;IDE下载链接&#xff09; …

Modbus tcp转ETHERCAT在Modbus软件中的配置方法

Modbus tcp和ETHERCAT是两种不同的协议&#xff0c;这给工业生产带来了很大的麻烦&#xff0c;因为这两种设备之间无法通讯。但是&#xff0c;捷米JM-ECT-TCP网关的出现&#xff0c;却为这个难题提供了解决方案。 JM-ECT-TCP网关能够连接到Modbus tcp总线和ETHERCAT总线中&…

C++ 关于大端小端的简析

大端及小端的简析 序言环境概念理解可能有问题的地方一般情况下需要注意的大小端情况关于大小端相关的实用函数/代码判断自身大小端的代码大小端转换函数 序言 我记得我已经查过4次了&#xff0c;最近回想一下发现我竟然又忘了&#xff01;所以特以此文来记录一下。 环境 Qt…

网络面试合集

传输层的数据结构是什么&#xff1f; 就是在问他的协议格式&#xff1a;UDP&TCP 2.1.1三次握手 通信前&#xff0c;要先建立连接&#xff0c;确保双方都是在线&#xff0c;具有数据收发的能力。 2.1.2四次挥手 通信结束后&#xff0c;会有一个断开连接的过程&#xff0…

Qsys介绍

文章目录 前言一、为什么需要Qsys1、简化了系统的设计流程2、Qsys涉及的技术 二、Qsys真身1、一种系统集成工具2、何为Nios II1、内核架构2、Nios II选型 三、Qsys设计涉及到的软件&工具四、总结五、参考资料 前言 Qsys是Altera下的一个系统集成工具&#xff0c;可用于搭建…