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

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

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

相关文章

Ansible 自动化运维工具

目录 一、概述 1.ansible 简介 2.ansible 特性 3.ansible 架构 二、ansible 环境安装部署 1.管理端安装 ansible&#xff08;192.168.88.10&#xff09; 2. ansible 工作目录 3. 配置主机清单 4.配置密钥对验证 三、ansible 命令行模块 1.command 模块 2.shell 模块…

牛客小白月赛76 E.括号序列操作专家(贪心)

氧气少年有一个长度为 n的括号序列&#xff0c;括号序列只包含左括号 ( 和右括号 )。 一个括号序列是合法的&#xff0c;当且仅当此括号序列可以通过插入加号 和数字 1 得到一个正确的算术表达式。例如&#xff1a;括号序列 (())()&#xff0c;()&#xff0c;和 (()(())) 都是…

7月27日,每日信息差

1、万科与万达长春合作项目纠纷已基本达成和解&#xff0c;万达商管部分被冻结股权即将解冻 2、WPS AI海外版开启公测.由OpenAI和PaLM2提供大模型支持。目前&#xff0c;WPS AI在Windows和Android端的WPS Office的文字和PDF组件上可用。未来&#xff0c;它将嵌入到文字、演示文…

Git基本操作

Git使用 1.命令行操作 1.1 本地库操作 1.1.1 本地库初始化 命令&#xff1a; git init 效果&#xff1a; 注意&#xff1a;.git目录中存放的是本地库相关的子目录和文件&#xff0c;不能删除和修改。 1.1.2 设置签名 作用&#xff1a;区分不同的开发人员身份 格式&…

思科路由器交换机密码破解教程

1. 路由器密码的恢复. 2600、3600等新系列路由器步骤&#xff1a; 1、启动路由器&#xff0c;60秒内按下ctrlbreak键2、rommon>confreg 0x21423、rommon>reset4、router#copy startup-config running-config5、router(config)#no enable secrect //可以删除密码也可以更…

Taskfile demo

https://github.com/yangyang5214/blog/issues/1 makefile 很好用&#xff0c;但是有些语法我不会。 go-task yml & shell 不错&#xff0c;推荐 Taskfile.yml https://github.com/go-task/task/blob/main/.golangci.yml # go install github.com/go-task/task/v3/cmd/ta…

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

【Matlab】基于BP神经网络的多输出数据回归预测(Excel可直接替换数据) 1.模型原理2.数学公式3.文件结构4.Excel数据5.分块代码6.完整代码7.运行结果1.模型原理 基于BP(Backpropagation)神经网络的多输出数据回归预测,是一种常见的机器学习方法,用于处理多个输出变量的回…

1 js嵌入html使用

1.1 直接在html内部使用js代码 使用script标签&#xff0c;在前后标签内部写的代码即为js代码。 <body><p id"p1">初始段落</p> <!--id是为了定位需要更改内容的标签--><button type"button" onclick"showNum()">…

Tesseract开源的OCR工具及python pytesseract安装使用

一 、介绍 Tesseract是一款由Google赞助的开源OCR。 pytesseract是python包装器&#xff0c;它为可执行文件提供了pythonic API。 Tesseract 已经有 30 年历史&#xff0c;开始它是惠普实验室的一款专利软件&#xff0c;在2005年后由Google接手并进一步开发和完善。Tesseract支…

使用Unsplash API生成随机图片

使用Unsplash API生成随机图片 1、默认随机 示例如下&#xff1a; https://source.unplash.com/random2、指定用户 可以从特定用户账号中生成随机图像。URL格式如下 https://source.unsplash.com/user/{USERNAME}点击示例1https://source.unsplash.com/user/angusyang9/li…

C++《i+1》

欢迎来到 PaQiuQiu 的空间 本文为【C《i1》专栏目录】&#xff0c;方便大家更好的阅读! 写在前面 当今计算机科学领域中最受欢迎和广泛使用的编程语言之一就是C。C是一种高级编程语言&#xff0c;具有强大的功能和广泛的应用领域&#xff0c;包括系统级编程、游戏开发、图形用…

tp5 链表查询,查出left表为空的数据

背景&#xff1a;tp5 A,B两表join链表查询&#xff0c;查出B表数据为空的A表数据 以及 B表数据不为空的A表数据 此操作将使用到 EXP 和 IS NULL 查出B表数据为空的A表数据SQL $where[] [exp,Db::raw("b.id IS NULL")];$list db(table1)->alias(a)->join(ta…

go语言中defer执行顺序

defer 执行顺序和调用顺序相反&#xff0c;类似于栈后进先出。 defer在 return 之后执行&#xff0c;但在函数推出之前&#xff0c;defer可以修改返回值。 func test() int {i : 0defer func() {fmt.Println("defer1")}()defer func() {i 1fmt.Println("defe…

YOLOv7 论文学习

1. 解决了什么问题&#xff1f; 实时的目标检测器是计算机视觉系统的重要组成部分。目前应用在 CPU 端的实时目标检测方法大多基于 MobileNet、ShuffleNet、GhostNet&#xff0c;而用在 GPU 的实时目标检测方法大多基于 ResNet、DarkNet、DLA&#xff0c;然后使用 CSPNet 策略…

Doris 部署

介绍 Apache Doris 是一个基于 MPP 架构的高性能、实时的分析型数据库&#xff0c;以极速易用的特点被人们所熟知&#xff0c;仅需亚秒级响应时间即可返回海量数据下的查询结果&#xff0c;不仅可以支持高并发的点查询场景&#xff0c;也能支持高吞吐的复杂分析场景。基于此&a…

MLP-Mixer:面向视觉的全mlp架构

文章目录 MLP-Mixer: An all-MLP Architecture for Vision摘要本文方法代码实验结果 MLP-Mixer: An all-MLP Architecture for Vision 摘要 卷积神经网络(cnn)是计算机视觉的首选模型。 最近&#xff0c;基于注意力的网络&#xff0c;如VIT&#xff0c;也变得流行起来。在本文…

@ImportResource 注解的使用

ImportResource注解&#xff1a;用于导入 Spring 的 xml 配置文件&#xff0c;让该配置文件中定义的 bean 对象加载到Spring容器中。 1.Spring 方式的配置文件 beans.xml <?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www…

【Logback】Spring boot 配置多环境的logback

一、背景描述 由于MAC环境本地启动项目存在目前权限问题&#xff0c;需要与测试环境不一致只&#xff0c;为了不每次修改代码都修改本地目录&#xff0c;则想配置日志目录的多环境支持 二、实现方案 1、application-local.yml配置 logging:config: classpath:logback-sprin…

leetcode刷题记录

1.二分法 class Solution { public:int search(vector<int> &nums, int target) {int left 0, right nums.size() - 1;while(left < right) {int mid left ((right - left) >> 1);if(nums[mid] > target) {right mid -1;} else if(nums[mid] < …

详解Linux手动释放缓存的方法

详解Linux手动释放缓存的方法 Linux释放内存的命令&#xff1a; sync echo 1 > /proc/sys/vm/drop_caches0&#xff1a;不释放&#xff08;系统默认值&#xff09; 1&#xff1a;释放页缓存 2&#xff1a;释放dentries和inodes 3&#xff1a;释放所有缓存 释放完内存后改回…