当前位置: 首页 > news >正文

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}" />

相关文章:

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

增加全局账户名同步 增加静态变量 添加文件&#xff1a;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; us…...

XGBoost的参数

目录 1. 迭代过程 1.1 迭代次数/学习率/初始&#x1d43b;最大迭代值 1.1.1 参数num_boost_round & 参数eta 1.1.2 参数base_score 1.1.3 参数max_delta_step 1.2 xgboost的目标函数 1.2.1 gamma对模型的影响 1.2.2 lambda对模型的影响 2. XGBoost的弱评估器 2.…...

【已解决】windows7添加打印机报错:加载Tcp Mib库时的错误,无法加载标准TCP/IP端口的向导页

windows7 添加打印机的时候&#xff0c;输入完打印机的IP地址后&#xff0c;点击下一步&#xff0c;报错&#xff1a; 加载Tcp Mib库时的错误&#xff0c;无法加载标准TCP/IP端口的向导页 解决办法&#xff1a; 复制以下的代码到新建文本文档.txt中&#xff0c;然后修改文本文…...

用于紫外线消毒灯的LED驱动:数明深紫外消毒方案SLM201

用于紫外线消毒灯的LED驱动SLM201 应用于紫外线消毒灯的LED驱动。疫情过后让越来越多的人开始注重起个人健康&#xff0c;除了出门佩戴口罩外&#xff0c;对于居家消毒也越发重视起来。而居家消毒除了75%浓度酒精及各类消毒液外&#xff0c;利用紫外线灯给衣物表面、房间消毒也…...

Docker部署Springboot应用【mysql部署+jar部署+Nginx部署】

【项目达到目标】 1.基本准备 2、mysql部署 3、jar部署 4、Nginx部署 一、基本准备 石工拿的就是之前放置在我们服务器上的应用进行部署&#xff0c;主要就是mysql和jar还有Vue的部署。 目前已经有的是jar、已经打包好的vue 二、mysql部署 docker run -d --name mysql \ …...

EMC VNX1系列存储电池状态说明

SPS电池正常的状态为“Present”。 SPS电池故障时的状态为“Faulted”。 更换SPS后&#xff0c;SPS开始充电&#xff0c;此时状态显示为“Not Ready”状态。 充电完成后显示为Present状态。如果充电完成后状态前面有“F”标记&#xff0c;则需要重启对应的控制器以更新SPS…...

pyspark 判断 Hive 表是否存在

Catalog.tableExists(tableName: str, dbName: Optional[str] None) → booltableName:表名 dbName&#xff1a;库名(可选) return&#xff1a;bool 值 spark SparkSession \.builder \.appName(tableExists) \.config(spark.num.executors, 6) \.config(spark.executor.memo…...

选择排序算法

选择排序 算法说明与代码实现&#xff1a; 以下是使用Go语言实现的选择排序算法示例代码&#xff1a; package mainimport "fmt"func selectionSort(arr []int) {n : len(arr)for i : 0; i < n-1; i {minIndex : ifor j : i 1; j < n; j {if arr[j] < a…...

快速了解MyBatis---映射关系多对一

文章目录 映射关系多对一映射关系-官方文档映射关系多对1-基本介绍基本介绍注意细节 映射关系多对1-映射方式映射方式配置Mapper.xml 方式-应用实例注解实现多对1 映射-应用实例 映射关系多对一 映射关系-官方文档 文档地址: https://mybatis.org/mybatis-3/zh/sqlmap-xml.ht…...

python学到什么程度算入门,python从入门到精通好吗

本篇文章给大家谈谈python学到什么程度算入门&#xff0c;以及python从入门到精通好吗&#xff0c;希望对各位有所帮助&#xff0c;不要忘了收藏本站喔。 学习 Python 之 进阶学习 一切皆对象 1. 变量和函数皆对象2. 模块和类皆对象3. 对象的基本操作 (1). 可以赋值给变量(2). …...

整数规划——第一章 引言

整数规划——第一章 引言 整数规划是带整数变量的最优化问题&#xff0c;即最大化或最小化一个全部或部分变量为整数的多元函数受约束于一组等式和不等式条件的最优化问题。许多经济、管理、交通、通信和工程中的最优化问题都可以用整数规划来建模。 考虑一个电视机工厂的生产…...

C语言结构体讲解

目录 结构体的声明 结构的基础知识 结构的声明 为什么要出现结构体&#xff1f; 结构成员的类型 结构体变量的定义和初始化 定义&#xff1a;&#xff08;全局变量//局部变量&#xff09; 初始化&#xff1a; 结构体成员的访问 结构体传参 结构体的声明 结构的基础知识…...

021 - STM32学习笔记 - Fatfs文件系统(三) - 细化与总结

021 - STM32学习笔记 - Fatfs文件系统&#xff08;三&#xff09; - 细化与总结 上节内容中&#xff0c;初步实现了FatFs文件系统的移植&#xff0c;并且实现了设备的挂载、文件打开/关闭与读写功能&#xff0c;这里对上节遗留的一些问题进行总结&#xff0c;并且继续完善文件…...

jQuery如何获取动态添加的元素

jQuery如何获取动态添加的元素 使用 on()方法 本质上使用了事件委派&#xff0c;将事件委派在父元素身上 自 jQuery 版本 1.7 起&#xff0c;on() 方法是 bind()、live() 和 delegate() 方法的新的替代品&#xff0c;但是由于on()方法必须有事件&#xff0c;没有事件时可选择de…...

Keepalived 在CentOS 7安装并配置监听MySQL双主

keepalived安装 MySQL双主配置请看这里&#xff1a;https://tongyao.blog.csdn.net/article/details/132016200?spm1001.2014.3001.5502 128、129两台服务器安装步骤相同&#xff0c;配置文件不同&#xff0c;下面有介绍。 1.安装相关依赖包&#xff0c;并下载keepalived安…...

深度学习,神经网络介绍

目录 1.神经网络的整体构架 2.神经网络架构细节 3.正则化与激活函数 4.神经网络过拟合解决方法 1.神经网络的整体构架 ConvNetJS demo: Classify toy 2D data 我们可以看看这个神经网络的网站&#xff0c;可以用来学习。 神经网络的整体构架如下1&#xff1a; 感知器&…...

中国AI大模型峰会“封神之作”!开发者不容错过这场夏季盛会

年度最强大模型顶会来袭&#xff01;喊话中国数百万AI开发者&#xff0c;速来&#xff01; 硬核来袭&#xff01;中国AI大模型峰会“封神之作”&#xff0c;开发者们不容错过! 前瞻大模型发展趋势&#xff0c;紧跟这场大会&#xff01; 中国科技超级碗&#xff0c;大模型最新前…...

Android Studio多渠道打包

使用环境&#xff1a; Android studio 多渠道打包 使用方法&#xff1a; 1 APP下build.gradle文件 flavorDimensions "default"productFlavors {huawei {dimension "default"manifestPlaceholders [ channel:"huawei" ]}xiaomi {dimension &…...

RK3566 Android11默认客户Launcher修改

前言 客户需要默认自己的Launcher为home,同时保留系统的Launcher3. 解决办法:在启动home应用之前设置一下默认Launcher。查找home app启动相关资料,找到了frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java的startHomeOnTaskDisplayA…...

ORB算法在opencv中实现方法

在OPenCV中实现ORB算法&#xff0c;使用的是&#xff1a; 1.实例化ORB orb cv.xfeatures2d.orb_create(nfeatures)参数&#xff1a; nfeatures: 特征点的最大数量 2.利用orb.detectAndCompute()检测关键点并计算 kp,des orb.detectAndCompute(gray,None)参数&#xff1a…...

应用升级/灾备测试时使用guarantee 闪回点迅速回退

1.场景 应用要升级,当升级失败时,数据库回退到升级前. 要测试系统,测试完成后,数据库要回退到测试前。 相对于RMAN恢复需要很长时间&#xff0c; 数据库闪回只需要几分钟。 2.技术实现 数据库设置 2个db_recovery参数 创建guarantee闪回点&#xff0c;不需要开启数据库闪回。…...

React hook之useRef

React useRef 详解 useRef 是 React 提供的一个 Hook&#xff0c;用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途&#xff0c;下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...

SciencePlots——绘制论文中的图片

文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了&#xff1a;一行…...

el-switch文字内置

el-switch文字内置 效果 vue <div style"color:#ffffff;font-size:14px;float:left;margin-bottom:5px;margin-right:5px;">自动加载</div> <el-switch v-model"value" active-color"#3E99FB" inactive-color"#DCDFE6"…...

Neo4j 集群管理:原理、技术与最佳实践深度解析

Neo4j 的集群技术是其企业级高可用性、可扩展性和容错能力的核心。通过深入分析官方文档,本文将系统阐述其集群管理的核心原理、关键技术、实用技巧和行业最佳实践。 Neo4j 的 Causal Clustering 架构提供了一个强大而灵活的基石,用于构建高可用、可扩展且一致的图数据库服务…...

Mac下Android Studio扫描根目录卡死问题记录

环境信息 操作系统: macOS 15.5 (Apple M2芯片)Android Studio版本: Meerkat Feature Drop | 2024.3.2 Patch 1 (Build #AI-243.26053.27.2432.13536105, 2025年5月22日构建) 问题现象 在项目开发过程中&#xff0c;提示一个依赖外部头文件的cpp源文件需要同步&#xff0c;点…...

LeetCode - 199. 二叉树的右视图

题目 199. 二叉树的右视图 - 力扣&#xff08;LeetCode&#xff09; 思路 右视图是指从树的右侧看&#xff0c;对于每一层&#xff0c;只能看到该层最右边的节点。实现思路是&#xff1a; 使用深度优先搜索(DFS)按照"根-右-左"的顺序遍历树记录每个节点的深度对于…...

GitFlow 工作模式(详解)

今天再学项目的过程中遇到使用gitflow模式管理代码&#xff0c;因此进行学习并且发布关于gitflow的一些思考 Git与GitFlow模式 我们在写代码的时候通常会进行网上保存&#xff0c;无论是github还是gittee&#xff0c;都是一种基于git去保存代码的形式&#xff0c;这样保存代码…...

push [特殊字符] present

push &#x1f19a; present 前言present和dismiss特点代码演示 push和pop特点代码演示 前言 在 iOS 开发中&#xff0c;push 和 present 是两种不同的视图控制器切换方式&#xff0c;它们有着显著的区别。 present和dismiss 特点 在当前控制器上方新建视图层级需要手动调用…...

MySQL JOIN 表过多的优化思路

当 MySQL 查询涉及大量表 JOIN 时&#xff0c;性能会显著下降。以下是优化思路和简易实现方法&#xff1a; 一、核心优化思路 减少 JOIN 数量 数据冗余&#xff1a;添加必要的冗余字段&#xff08;如订单表直接存储用户名&#xff09;合并表&#xff1a;将频繁关联的小表合并成…...