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

WPF实战学习笔记18-优化设计TodoView

文章目录

    • 优化设计TodoView
      • 修复新增项目无法编辑问题
      • 增加了对完成状态的区分
      • 增加了选项卡删除功能
        • 更新删除请求URI
        • 添加删除命令并初始化
        • UI添加删除按钮
        • 更改控制器
      • 增加查询结果为空的图片
        • 增加转换器
        • 修改UI
          • 添加资源、命名空间
        • 添加相关元素
      • 增加了根据状态查询的功能
        • Mytodo.Service/ITodoService增加GetAllFilterAsync接口
        • 修改了控制器
        • 增加IToDoService接口
        • 增加所需字段,属性,以及所需要的方法
        • UI层增加绑定的界面
        • 增加了IToDoService接口所对应的实现
      • 修复更新操作无法更新状态的bug
      • 修复当Search为空时查询失败的bug

优化设计TodoView

修复新增项目无法编辑问题

更新MyToDo.Api/Service/ToDoService.cs

public async Task<ApiReponse> AddAsync(Todo model)
{try{var todo = mapper.Map<Todo>(model);await work.GetRepository<Todo>().InsertAsync(todo);if (await work.SaveChangesAsync() > 0)return new ApiReponse(true, todo);return new ApiReponse(false);}catch (Exception ex){return new ApiReponse(false, ex);}
}

更新MyToDo.Api/Service/MemoService.cs

        public async Task<ApiReponse> AddAsync(Memo model){try{var memo = mapper.Map<Memo>(model);await work.GetRepository<Memo>().InsertAsync(memo);if (await work.SaveChangesAsync() > 0)return new ApiReponse(true, memo);return new ApiReponse(false);}catch (Exception ex){return new ApiReponse(false, ex);}}

增加了对完成状态的区分

更新MyToDo.Api/Service/TodoView.xaml

<ItemsControl.ItemTemplate><DataTemplate><Border MinWidth="200" Margin="10"><Border.Style><Style TargetType="Border"><Style.Triggers><DataTrigger Binding="{Binding Status}" Value="0"><Setter Property="Background" Value="#1E90FF" /></DataTrigger><DataTrigger Binding="{Binding Status}" Value="1"><Setter Property="Background" Value="#3CB371" /></DataTrigger></Style.Triggers></Style></Border.Style><Grid MinHeight="150">

增加了选项卡删除功能

更新删除请求URI

更新MyToDo.Api/Service/Baservice.cs

    public async Task<ApiResponse> DeleteAsync(int id){BaseRequest request = new BaseRequest();request.Method = RestSharp.Method.DELETE;request.Route = $"api/{ServiceName}/Delete?todoid={id}";return await client.ExecuteAsync(request);}

添加删除命令并初始化

更新文件:MyToDo/ViewModel/TodoViewModel.cs

添加内容:

/// <summary>
/// 删除项
/// </summary>
public DelegateCommand<ToDoDto> DeleteCommand { get; set; }/// <summary>
/// 删除指定项
/// </summary>
/// <param name="dto"></param>
async private void DeleteItem(ToDoDto dto)
{var delres = await service.DeleteAsync(dto.Id);if (delres.Status){var model = TodoDtos.FirstOrDefault(t => t.Id.Equals(dto.Id));TodoDtos.Remove(dto);}
}  

更新内容

public TodoViewModel(ITodoService service,IContainerProvider provider) : base(provider)
{//初始化对象TodoDtos = new ObservableCollection<ToDoDto>();  RightContentTitle = "添加血雨待办";//初始化命令SelectedCommand         = new DelegateCommand<ToDoDto>(Selected);OpenRightContentCmd     = new DelegateCommand(Add);ExecuteCommand          = new DelegateCommand<string>(ExceuteCmd);DeleteCommand           = new DelegateCommand<ToDoDto>(DeleteItem);this.service = service;
}

UI添加删除按钮

更新文件:MyToDo/Views/TodoView.cs

更新内容:

<Grid MinHeight="150"><!--  给项目添加行为  --><i:Interaction.Triggers><i:EventTrigger EventName="MouseLeftButtonUp"><i:InvokeCommandAction Command="{Binding DataContext.SelectedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}" CommandParameter="{Binding}" /></i:EventTrigger></i:Interaction.Triggers><Grid.RowDefinitions><RowDefinition Height="auto" /><RowDefinition /></Grid.RowDefinitions><DockPanel Panel.ZIndex="2" LastChildFill="False"><TextBlockMargin="10,10"FontFamily="黑体"FontSize="14"Text="{Binding Title}" /><!--<md:PackIconMargin="10,10"VerticalContentAlignment="Top"DockPanel.Dock="Right"Kind="More" />--><md:PopupBoxMargin="5"Panel.ZIndex="1"DockPanel.Dock="Right"><ButtonPanel.ZIndex="2"Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}"CommandParameter="{Binding}"Content="删除" /></md:PopupBox></DockPanel>

更改控制器

更新文件:MyToDo.Api/Controllers/TodoController.cs

更新内容:

public async Task<ApiReponse> Delete(int todoid)=> await service.DeleteAsync(todoid);

增加查询结果为空的图片

增加转换器

添加文件:MyToDo/Common/Converters/IntToVisibilityConveter.cs

更新内容:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;namespace Mytodo.Common.Converters
{[ValueConversion(typeof(Color), typeof(Brush))]public class ColorToBrushConverter : IValueConverter{public object Convert(object value, Type targetType, object parameter, CultureInfo culture){if (value is Color color){return new SolidColorBrush(color);}return Binding.DoNothing;}public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){if (value is SolidColorBrush brush){return brush.Color;}return default(Color);}}
}

修改UI

添加资源、命名空间

更新文件:MyToDo/Views/Converters/TodoView.xaml.cs

更新内容:

xmlns:cv="clr-namespace:Mytodo.Common.Converters"   <UserControl.Resources><ResourceDictionary><cv:IntToVisibilityConveter x:Key="IntToVisility" /></ResourceDictionary>
</UserControl.Resources>

添加相关元素

FontSize="14" />
<StackPanelGrid.Row="1"VerticalAlignment="Center"Visibility="{Binding TodoDtos.Count, Converter={StaticResource IntToVisility}}"><ImageWidth="120"Height="120"Source="/Images/nores.jpg" /><TextBlockMargin="0,10"HorizontalAlignment="Center"FontSize="18"Text="尝试添加一些待办事项,以便在此处查看它们。" />
</StackPanel>
<ItemsControl

增加了根据状态查询的功能

Mytodo.Service/ITodoService增加GetAllFilterAsync接口

using Mytodo.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyToDo.Share.Models;
using MyToDo.Share.Contact;
using MyToDo.Share.Parameters;
using MyToDo.Share;namespace Mytodo.Service
{public interface ITodoService:IBaseService<ToDoDto>{Task<ApiResponse<PagedList<ToDoDto>>> GetAllFilterAsync(TodoParameter parameter);}
}

修改了控制器

MyToDo.Api.Controllers/TodoController

[HttpGet]
public async Task<ApiReponse> GetAll([FromQuery] TodoParameter param) => await service.GetAllAsync(param);

增加IToDoService接口

MyToDo.Api.Service/IToDoService

namespace MyToDo.Api.Service
{public interface IToDoService : IBaseService<Todo>{Task<ApiReponse> GetAllAsync(TodoParameter parameter);}
}

增加所需字段,属性,以及所需要的方法

更新文件:Mytodo.ViewModels/TodoViewModel.cs

/// <summary>
/// 项目状态
/// </summary>
public int SelectIndex
{get { return selectIndex; }set { selectIndex = value; RaisePropertyChanged(); }
}private int selectIndex;/// <summary>
/// 保存消息
/// </summary>
private async void Save()
{try{if (string.IsNullOrWhiteSpace(CurrDto.Title) || string.IsNullOrWhiteSpace(CurrDto.Content))return;UpdateLoding(true);if(CurrDto.Id>0) //编辑项{var updateres = await service.UpdateAsync(CurrDto);if (updateres.Status){UpdateDataAsync();}else{MessageBox.Show("更新失败");}}else{       //添加项var add_res =   await service.AddAsync(CurrDto);//刷新if (add_res.Status) //如果添加成功{TodoDtos.Add(add_res.Result);}else{MessageBox.Show("添加失败");}}}catch{}finally{IsRightOpen = false;//卸载数据加载窗体UpdateLoding(false);}
}/// <summary>
/// 打开待办事项弹窗
/// </summary>
void Add()
{CurrDto = new ToDoDto();IsRightOpen = true;
}private void Query()
{GetDataAsync();
}/// <summary>
/// 根据条件更新数据
/// </summary>
async void UpdateDataAsync()
{int? Status = SelectIndex == 0 ? null : SelectIndex == 2 ? 1 : 0;var todoResult = await service.GetAllFilterAsync(new MyToDo.Share.Parameters.TodoParameter { PageIndex = 0, PageSize = 100, Search = SearchString, Status = Status });if (todoResult.Status){todoDtos.Clear();foreach (var item in todoResult.Result.Items)todoDtos.Add(item);}
}/// <summary>
/// 获取所有数据
/// </summary>
async void GetDataAsync()
{//调用数据加载页面UpdateLoding(true);//更新数据UpdateDataAsync();//卸载数据加载页面UpdateLoding(false);
}

UI层增加绑定的界面

<ComboBox Margin="5" SelectedIndex="{Binding CurrDto.Status}"><ComboBoxItem Content="已完成" FontSize="12" /><ComboBoxItem Content="未完成" FontSize="12" />
</ComboBox>
<StackPanelGrid.Row="1"VerticalAlignment="Center"Visibility="{Binding TodoDtos.Count, Converter={StaticResource IntToVisility}}"><md:PackIconWidth="120"Height="120"HorizontalAlignment="Center"Kind="ClipboardText" /><TextBlockMargin="0,10"HorizontalAlignment="Center"FontSize="18"Text="尝试添加一些待办事项,以便在此处查看它们。" />

增加了IToDoService接口所对应的实现

public async Task<ApiReponse> GetAllAsync(QueryParameter parameter)
{try{var repository = work.GetRepository<Todo>();var todos = await repository.GetPagedListAsync(predicate:x => string.IsNullOrWhiteSpace(parameter.Search) ? true : x.Title.Contains(parameter.Search),pageIndex: parameter.PageIndex,pageSize: parameter.PageSize,orderBy: source => source.OrderByDescending(t => t.CreateDate));return new ApiReponse(true, todos);}catch (Exception ex){return new ApiReponse(ex.Message,false);}
}

修复更新操作无法更新状态的bug

    public async Task<ApiReponse> UpdateAsync(Todo model){try{var dbtodo = mapper.Map<Todo>(model);//获取数据var resposity = work.GetRepository<Todo>();//var todo = await resposity.GetFirstOrDefaultAsync(predicate: x => x.Id.Equals(dbtodo.Id));if(todo == null)return new ApiReponse("修改失败,数据库中无给定条件的数据项",false);todo.Title= dbtodo.Title;todo.UpdateDate=DateTime.Now;todo.CreateDate = dbtodo.CreateDate;todo.Content = dbtodo.Content;todo.Status = dbtodo.Status;resposity.Update(todo);if (await work.SaveChangesAsync() > 0)return new ApiReponse(true);return new ApiReponse(false);}catch (Exception ex){return new ApiReponse(ex.Message, false);}}

修复当Search为空时查询失败的bug

Mytodo.Service/TodoService.cs

public async Task<ApiResponse<PagedList<ToDoDto>>> GetAllFilterAsync(TodoParameter parameter)
{BaseRequest request = new BaseRequest();request.Method = RestSharp.Method.GET;var parameter_search = parameter.Search;if(parameter_search==null){request.Route = $"api/ToDo/GetAll?pageIndex={parameter.PageIndex}" +$"&pageSize={parameter.PageSize}" +$"&status={parameter.Status}";}elserequest.Route = $"api/ToDo/GetAll?pageIndex={parameter.PageIndex}" +$"&pageSize={parameter.PageSize}" +$"&search={parameter.Search}" +$"&status={parameter.Status}";return await client.ExecuteAsync<PagedList<ToDoDto>>(request);
}

相关文章:

WPF实战学习笔记18-优化设计TodoView

文章目录 优化设计TodoView修复新增项目无法编辑问题增加了对完成状态的区分增加了选项卡删除功能更新删除请求URI添加删除命令并初始化UI添加删除按钮更改控制器 增加查询结果为空的图片增加转换器修改UI添加资源、命名空间 添加相关元素 增加了根据状态查询的功能Mytodo.Serv…...

Python版day59

503. 下一个更大元素 II 给定一个循环数组 nums &#xff08; nums[nums.length - 1] 的下一个元素是 nums[0] &#xff09;&#xff0c;返回 nums 中每个元素的 下一个更大元素 。 数字 x 的 下一个更大的元素 是按数组遍历顺序&#xff0c;这个数字之后的第一个比它更大的数&…...

[SQL挖掘机] - 算术运算符

在 sql 中&#xff0c;算术运算符主要用于执行数值计算操作&#xff0c;并且在查询语句中具有重要的地位。下面是算术运算符在 sql 中的一些作用和地位&#xff1a; 进行数值计算&#xff1a;算术运算符可以对数值类型的数据进行加减乘除等数值计算操作。例如&#xff0c;可以…...

机器学习基础 数据集、特征工程、特征预处理、特征选择 7.27

机器学习基础 1. 数据集 2. 特征工程 3. 学习分类 4. 模型 5. 损失函数 6. 优化 7. 过拟合 8. 欠拟合数据集 又称资料集、数据集合或者资料集合&#xff0c;是一种由数据所组成的集合特征工程 1. 特征需求 2. 特征设计 3. 特征处理特征预处理、特征选择、特征降维 4. 特征验…...

Sass 常用的功能!

Sass 常用功能 Sass 功能有很多&#xff0c;这边只列举一些比较常用的。 嵌套规则 (Nested Rules) Sass 允许将一套 CSS 样式嵌套进另一套样式中&#xff0c;内层的样式将它外层的选择器作为父选择器。 编译前 .box {.box1 {background-color: red;}.box2 {background-col…...

chmod命令详细使用说明

chmod命令详细使用说明 chmod是Unix和类Unix系统上用于更改文件或目录权限的命令。它是"change mode"的缩写。在Linux和其他类Unix操作系统中&#xff0c;文件和目录具有权限位&#xff0c;用来控制哪些用户可以访问、读取、写入或执行它们。chmod命令允许用户修改这…...

ICC2如何计算Gate Count?

我正在「拾陆楼」和朋友们讨论有趣的话题&#xff0c;你⼀起来吧&#xff1f;知识星球入口 我们认为gate count等于standard cell(非physical only)总面积 / 最小驱动二输入与非门面积。 ICC2没有专门的命令去报告gate count&#xff0c;只能自己计算&#xff0c;使用report_d…...

Qtday3作业

作业 头文件 #ifndef WIDGET_H #define WIDGET_H#include <QPushButton> #include <QTextToSpeech> #include <QWidget> #include <QDebug> #include <QTimer> //定时器类 #include <QTime> //时间类 #include <QTimerEvent>…...

全球程序员需要知道的50+网址,有多少你第一次听说?

作为程序员&#xff0c;需要知道的50网址&#xff0c;有多少你第一次听说 GitHub (github.com): 最大的代码托管平台&#xff0c;开源项目和代码分享的社区。程序员可以在这里找到各种有趣的项目&#xff0c;参与开源贡献或托管自己的代码。 Stack Overflow (stackoverflow.co…...

Matlab中实现对一幅图上的局部区域进行放大

大家好&#xff0c;我是带我去滑雪&#xff01; 局部放大图可以展示图像中的细节信息&#xff0c;使图像更加直观和精美&#xff0c;此次使用magnify工具实现对绘制的figure选择区域绘制&#xff0c;图像效果如下&#xff1a; 1、基本图像绘制 这里选择绘制一个散点图&#xff…...

mysql-速成补充

目录 1.演示事务 ​编辑 1.1 read-uncommitted 1.2 read-committed 1.3 repeatable read 1.4 幻读 1.5 serializable 1.6 savepoint 2 变量 2.1 语法 2.2 举例 3 存储过程和函数 3.1 特点和语法 3.2 举例 4.函数 4.1 语法 4.2 举例 5 流程控制 5.1 分…...

微信小程序,商城底部工具栏的实现

效果演示&#xff1a; 前提条件&#xff1a; 去阿里云矢量图标&#xff0c;下载8个图标&#xff0c;四个黑&#xff0c;四个红&#xff0c;如图&#xff1a; 新建文件夹icons&#xff0c;把图标放到该文件夹&#xff0c;然后把该文件夹移动到该项目的文件夹里面。如图所示 app…...

Lab———Git使用指北

Lab———Git使用指北 &#x1f916;:使用IDEA Git插件实际工作流程 &#x1f4a1; 本文从实际使用的角度出发&#xff0c;以IDEA Git插件为基本讲述了如果使用IDEA的Git插件来解决实际开发中的协作开发问题。本文从 远程仓库中拉取项目&#xff0c;在本地分支进行开发&#x…...

ChatGPT的工作原理:从输入到输出

&#x1f337;&#x1f341; 博主 libin9iOak带您 Go to New World.✨&#x1f341; &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33…...

redis数据库与主从复制

目录 一 基本操作 二 执行流程 三 reids持久化 四 rdb和aof持久化的过程 五 为什么会有内存碎片 六 redis组从复制 一 基本操作 set :存放数据 例如 set 键值 内容 set k kokoko k就是键值 kokoko就是内容 get:获取数据 例如 get k 就会出来 k对应的数据 keys 查询键…...

js加载和长任务

js加载和长任务 本文将讲解以下浏览器如何加载js&#xff0c;并介绍一些可以提高网页加载速度的方法。 Evaluate Script 如果我们在devtools的performance中分析过网站的加载性能&#xff0c;可能会看到一个很长的任务&#xff0c;叫做Evaluate Script. 在这种情况下&#x…...

利用Stable diffusion Ai 制作艺术二维码超详细参数和教程

大家有没有发现最近这段时间网上出现了各种各样的AI艺术二维码&#xff0c;这种二维码的出现&#xff0c;简直是对二维码的“颠覆式创新”&#xff0c;直接把传统的二维码提升了一个维度&#xff01;作为设计师的我们怎么可以不会呢&#xff1f; 今天就教大家怎么制作这种超有艺…...

【C语言课程设计】图书管理系统

引言&#xff1a; 图书管理系统是一个重要的信息管理系统&#xff0c;对于图书馆和书店等机构来说&#xff0c;它能够方便地管理图书的录入、显示、查询、修改和删除等操作。本实验基于C语言开发了一个简单的图书管理系统&#xff0c;通过账户名和密码进行系统访问和权限控制&a…...

在 ArcGIS Pro 中使用 H3 创建蜂窝六边形

H3是Uber开发的分层索引系统,它使用六边形来平铺地球表面。H3在二十面体(一个具有20个三角形面和12个顶点的形状)上构建其六边形网格。由于仅用六边形不可能平铺二十面体,因此每个分辨率需要12个五边形来完成网格。分层索引网格意味着每个六边形都可以细分为子单元六边形。…...

创建Electron项目

一、使用vite 构建 electron项目 npm init vitelatest Need to install the following packages:create-vitelatest Ok to proceed? (y) y √ Project name: ... CertificateDownload √ Package name: ... certificatedownload √ Select a framework: Vue √ Select a var…...

Spring Boot实践一

一、Spring Boot简介 Spring Boot是一个基于Spring框架的快速开发应用程序的工具。它提供了一种快速、方便的方式来创建基于Spring的应用程序&#xff0c;而无需繁琐的配置。Spring Boot通过自动配置和约定大于配置的方式&#xff0c;使得开发者可以更加专注于业务逻辑的实现&…...

简单认识NoSQL的Redis配置与优化

文章目录 一、关系型数据库与非关系型数据库1、关系型数据库&#xff1a;2、非关系型数据库3、关系型数据库和非关系型数据库区别&#xff1a;4、非关系型数据库应用场景 二.Redis1、简介2、优点&#xff1a;3、Redis为什么这么快&#xff1f; 三、Redis 安装部署1、安装配置2、…...

开发一个RISC-V上的操作系统(二)—— 系统引导程序(Bootloader)

目录 文章传送门 一、什么是Bootloader 二、简单的启动程序 三、上板测试 文章传送门 开发一个RISC-V上的操作系统&#xff08;一&#xff09;—— 环境搭建_riscv开发环境_Patarw_Li的博客-CSDN博客 开发一个RISC-V上的操作系统&#xff08;二&#xff09;—— 系统引导…...

Git安装与学习

Git学习网站 Git安装教程 镜像网站 https://registry.npmmirror.com/binary.html 镜像下载是网站对服务器的一个保护措施之一&#xff0c;就是A站点下载的数据同 B站点下载的数据完全一样&#xff0c;b站点就是A站点的一面镜子。 所以镜像下载下来和原站点一摸一样。...

【Docker】docker中容器之间通信方式

文章目录 1. Docker容器之间通信的主要方式1.1 通过容器ip访问1.2. 通过宿主机的ip:port访问1.3. 通过link建立连接&#xff08;官方不推荐使用&#xff09;1.4. 通过 User-defined networks&#xff08;推荐&#xff09; 2. 参考资料 1. Docker容器之间通信的主要方式 1.1 通…...

算法-归并排序-JAVA

下面是Java实现归并排序的示例代码&#xff1a; public class MergeSort {public void mergeSort(int[] arr) {if (arr null || arr.length < 1) {return;}int[] temp new int[arr.length];mergeSort(arr, temp, 0, arr.length - 1);}private void mergeSort(int[] arr, …...

Flask 进阶

Flask 如何访问项目以外的文件 在工作中&#xff0c; 要在项目里展示一些额外的文件&#xff0c; 包括但不限于静态的html。图片&#xff0c; log&#xff0c; 其他的都还好说&#xff0c; 但是当html的时候我就开始犯难了&#xff0c; 因为数量过多 我并不想把它塞进我项目的t…...

home-assistant整合sso

其他软件都可以通过nginx直接做代理添加鉴权&#xff0c;但是这个hass果然是用户安全隐私很强&#xff0c;做代理需要配置白名单&#xff0c;而且支持的三方鉴权都不太适合我的需求&#xff0c;非要改源码才行&#xff0c;后来我发现不用改源码的折中方式 参考文章 External …...

Ip-Limit: 轻量级注解式IP限流组件(二)

author: van , ggfanwentaogmail.comIp-Limit-Example: 轻量级注解式IP限流组件使用样例 项目简介 该项目为ip-limiter的使用示例项目。 ip-limiter地址&#xff1a; https://github.com/DDAaTao/ip-limiter 示例项目文件树 └─example├─handler│ └─BaseException…...

【C++】开源:Redis数据库配置与使用

&#x1f60f;★,:.☆(&#xffe3;▽&#xffe3;)/$:.★ &#x1f60f; 这篇文章主要介绍Redis数据库配置与使用。 无专精则不能成&#xff0c;无涉猎则不能通。。——梁启超 欢迎来到我的博客&#xff0c;一起学习&#xff0c;共同进步。 喜欢的朋友可以关注一下&#xff0c…...