Notes d'étude pratique WPF 25-Résumé de la page d'accueil

REMARQUE : Cette implémentation ne correspond pas à la vidéo. Dans cette implémentation, l'interface récapitulative est créée séparément, tandis que la vidéo est fusionnée dans l'interface todo nationale.

  • Ajouter une interface webapi récapitulative
  • Ajouter une interface client de données récapitulatives
  • Station d'accueil totale de l'interface client de données 3
  • Accueil Modèle de données

Ajouter une classe de champ de résumé de données

Créer un nouveau fichier MyToDo.Share.Models.SummaryDto

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.Share.Models
{
    public class SummaryDto:BaseDto
    {
		private int sum;

		public int Sum
		{
			get { return sum; }
			set { sum = value; OnPropertyChanged(); }
		}

		private int compeleteCnt;

		public int CompeleteCnt
		{
			get { return compeleteCnt; }
			set { compeleteCnt = value; OnPropertyChanged(); }
		}

		private int  memoCnt;

		public int  MemoCnt
		{
			get { return memoCnt; }
			set { memoCnt = value; OnPropertyChanged(); }
		}


		private string? compeleteRatio;

		public string? CompeleteRatio
        {
			get { return compeleteRatio; }
			set { compeleteRatio = value; OnPropertyChanged(); }
		}


		private ObservableCollection<ToDoDto> todoList;

		public ObservableCollection<ToDoDto> TodoList
        {
			get { return todoList; }
			set { todoList = value; }
		}

        /// <summary>
        /// MemoList
        /// </summary>
        private ObservableCollection<MemoDto> memoList;

        public ObservableCollection<MemoDto> MemoList
        {
            get { return memoList; }
            set { memoList = value; }
        }

    }
}

Ajouter une interface webapi récapitulative

Ajouter une interface récapitulative

Ajouter un fichier : MyToDo.Api.Service.ISummary

using MyToDo.Share.Parameters;

namespace MyToDo.Api.Service
{
    public interface ISummary
    {
        Task<ApiReponse> GetAllInfo(SummaryParameter parameter);
    }
}

Implémenter l'interface de synthèse

Ajouter un fichier : MyToDo.Api.Service.Summary

using Arch.EntityFrameworkCore.UnitOfWork;
using AutoMapper;
using MyToDo.Api.Context;
using MyToDo.Share.Models;
using MyToDo.Share.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace MyToDo.Api.Service
{
    public class Summary : ISummary
    {
        private readonly IUnitOfWork work;
        private readonly IMapper mapper;

        public Summary(IUnitOfWork work,IMapper mapper)
        {
            this.work = work;
            this.mapper = mapper;
        }

        public async Task<ApiReponse> GetAllInfo(SummaryParameter parameter)
        {
            try
            {
                SummaryDto sumdto = new SummaryDto();

                //获取所有todo信息
                var Pagetodos = await work.GetRepository<Todo>().GetPagedListAsync(pageIndex: parameter.PageIndex, pageSize: parameter.PageSize, orderBy: source => source.OrderByDescending(t => t.CreateDate));

                //获取所有memo信息
                var Pagememos = await work.GetRepository<Memo>().GetPagedListAsync(pageIndex: parameter.PageIndex, pageSize: parameter.PageSize, orderBy: source => source.OrderByDescending(t => t.CreateDate));

                //汇总待办数量
                sumdto.Sum = Pagetodos.TotalCount;

                //统计完成数量
                var todos = Pagetodos.Items;
                sumdto.CompeleteCnt = todos.Where(t => t.Status == 1).Count();

                //计算已完成比率
                sumdto.CompeleteRatio = (sumdto.CompeleteCnt / (double)sumdto.Sum).ToString("0%");

                //统计备忘录数量
                var memos = Pagememos.Items;
                sumdto.MemoCnt=Pagememos.TotalCount;

                //获取todos项目与memos项目集合
                sumdto.TodoList = new ObservableCollection<ToDoDto>(mapper.Map<List<ToDoDto>>(todos.Where(t => t.Status == 0)));
                sumdto.MemoList = new ObservableCollection<MemoDto>(mapper.Map<List<MemoDto>>(memos));

                return new ApiReponse(true, sumdto);
            }
            catch (Exception ex)
            {
                return new ApiReponse(false, ex);
            }
        }
    }
}

ajouter un contrôleur

Ajouter le fichier MyToDo.Api.Controllers.SummaryController

using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using MyToDo.Api.Service;
using MyToDo.Share.Models;
using MyToDo.Share.Parameters;

namespace MyToDo.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class SummaryController:ControllerBase
    {
        private readonly ISummary service;

        public SummaryController(ISummary tService)
        {
            this.service = tService;
        }

        [HttpGet]
        public async Task<ApiReponse> GetAllInfo([FromQuery] SummaryParameter parameter)=>await service.GetAllInfo(parameter);

    }
}

injection de dépendance

Fichier : webapi.Program.cs

Ajouter à:

builder.Services.AddTransient<ISummary, Summary>();

Ajouter une interface de données client

ajouter une interface

Nouveau fichier : Mytodo.Service.ISummeryService.cs

using MyToDo.Share;
using MyToDo.Share.Contact;
using MyToDo.Share.Models;
using MyToDo.Share.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.Service
{
    public interface ISummeryService
    {
        //public async Task<ApiResponse<SummaryDto>> GetAllInfo(SummaryParameter parameter)
        Task<ApiResponse<SummaryDto>> GetAllInfo(SummaryParameter parameter);
    }
}

implémenter l'interface

Ajouter un fichier : Mytodo.Service.SummeryService

using MyToDo.Share;
using MyToDo.Share.Contact;
using MyToDo.Share.Models;
using MyToDo.Share.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.Service
{
    public class SummeryService : ISummeryService
    {
        private readonly HttpRestClient client;
        private readonly string ServiceName="Summary";

        public SummeryService(HttpRestClient client)
        {
            this.client = client;
        }

        public async Task<ApiResponse<SummaryDto>> GetAllInfo(SummaryParameter parameter)
        {

            BaseRequest request = new BaseRequest();

            request.Method = RestSharp.Method.GET;

            //如果查询字段为空
 
            request.Route = $"api/{ServiceName}/GetAllInfo?PageIndex={parameter.PageIndex}" + $"&PageSize={parameter.PageSize}";
            
                //request.Route = $"api/{ServiceName}/GetAll?PageIndex={parameter.PageIndex}" + $"&PageSize={parameter.PageSize}" + $"&search={parameter.Search}";

            return await client.ExecuteAsync<SummaryDto>(request);
        }
    }
}

injection de dépendance

Modifier le fichier App.xaml.cs pour ajouter du contenu

containerRegistry.Register<ISummeryService, SummeryService>();

Interface d'accueil

Modifier la liaison de la couche d'interface utilisateur

Modifiez le fichier : Mytodo.Views.IndexView.xaml

Dépend de

ItemsSource="{Binding TodoDtos}"
ItemsSource="{Binding MemoDtos}"

Changer en

ItemsSource="{Binding Summary.TodoList}"
ItemsSource="{Binding Summary.MemoList}"

Créer une nouvelle instance récapitulative et l'initialiser

Modifier le fichier : Mytodo.ViewModels.IndexViewModel.cs

public SummaryDto Summary
{
    get { return summary; }
    set { summary = value; RaisePropertyChanged(); }
}
private SummaryDto summary;

Créer une nouvelle instance de service de synthèse et l'initialiser

private readonly ISummeryService summService;
public IndexViewModel(IContainerProvider provider,
                      IDialogHostService dialog) : base(provider)
{
    //实例化接口
    this.toDoService= provider.Resolve<ITodoService>();
    this.memoService = provider.Resolve<IMemoService>();
    this.summService= provider.Resolve<ISummeryService>();

    //初始化命令
    EditMemoCmd = new DelegateCommand<MemoDto>(Addmemo);
    EditTodoCmd = new DelegateCommand<ToDoDto>(Addtodo);
    ToDoCompltedCommand = new DelegateCommand<ToDoDto>(Compete);
    ExecuteCommand = new DelegateCommand<string>(Execute);

    this.dialog = dialog;

    CreatBars();
}

Ajouter une fonction d'initialisation des données de la page d'accueil

/// <summary>
/// 更新首页所有信息
/// </summary>
private async void UpdateData()
{
    UpdateLoding(true);

    var summaryResult = await summService.GetAllInfo(new SummaryParameter() { PageIndex = 0, PageSize = 1000 });

    if (summaryResult.Status)
    {
        Summary = summaryResult.Result;
        Refresh();
    }

    UpdateLoding(false);
}
public override async void OnNavigatedTo(NavigationContext navigationContext)
{
    UpdateData();

    base.OnNavigatedTo(navigationContext);
}

void Refresh()
{
    TaskBars[0].Content = summary.Sum.ToString();
    TaskBars[1].Content = summary.CompeleteCnt.ToString();
    TaskBars[2].Content = summary.CompeleteRatio;
    TaskBars[3].Content = summary.MemoCnt.ToString();
}

Remplacez TodoDtos et MemoDtos par le champ récapitulatif

mettre à jour ajouter, modifier, terminer la commande

Le code modifié est :

using Mytodo.Common.Models;
using MyToDo.Share.Parameters;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using MyToDo.Share.Models;
using Prism.Commands;
using Prism.Services.Dialogs;
using Mytodo.Dialog;
using Mytodo.ViewModels;
using Mytodo.Service;
using Prism.Ioc;
using System.Diagnostics;
using Microsoft.VisualBasic;
using ImTools;
using DryIoc;
using MyToDo.Share;
using System.Windows;
using Prism.Regions;

namespace Mytodo.ViewModels
{
    public class IndexViewModel:NavigationViewModel
    {
        #region 定义命令


        /// <summary>
        /// Todo完成命令
        /// </summary>
        public DelegateCommand<ToDoDto> ToDoCompltedCommand { get; set; }
        public DelegateCommand<string> ExecuteCommand { get; set; }

        /// <summary>
        /// 命令:编辑备忘
        /// </summary>
        public DelegateCommand<MemoDto> EditMemoCmd { get;private set; }

        /// <summary>
        /// 命令:编辑待办
        /// </summary>
        public DelegateCommand<ToDoDto> EditTodoCmd { get; private set; }


        #endregion

        #region 定义属性



        public SummaryDto Summary
        {
            get { return summary; }
            set { summary = value; RaisePropertyChanged(); }
        }


        public string Title { get; set; }


        /// <summary>
        /// 首页任务条
        /// </summary>
        public ObservableCollection<TaskBar> TaskBars
        {
            get { return taskBars; }
            set { taskBars = value; RaisePropertyChanged(); }
        }
        #endregion

        #region 定义重要命令

        #endregion

        #region 定义重要字段
        private readonly IDialogHostService dialog;
        private readonly ITodoService toDoService;
        private readonly ISummeryService summService;
        private readonly IMemoService memoService;
        #endregion

        #region 定义普通字段
        private SummaryDto summary;
        private ObservableCollection<TaskBar> taskBars;
        #endregion

        #region 命令相关方法

        /// <summary>
        /// togglebutoon 的命令
        /// </summary>
        /// <param name="dto"></param>
        /// <exception cref="NotImplementedException"></exception>
        async private void Compete(ToDoDto dto)
        {
            if (dto == null || string.IsNullOrEmpty(dto.Title) || (string.IsNullOrEmpty(dto.Content)))
                return;

            var updres = await toDoService.UpdateAsync(dto);

            if (updres.Status)
            {
                var todo = Summary.TodoList.FirstOrDefault(x => x.Id.Equals(dto.Id));
                //更新信息
                todo.Status = dto.Status;
            }

            // 从数据库更新信息
            UpdateData();
        }

        /// <summary>
        /// 选择执行命令
        /// </summary>
        /// <param name="obj"></param>
        void Execute(string obj)
        {
            switch (obj)
            {
                case "新增待办": Addtodo(null); break;
                case "新增备忘": Addmemo(null); break;
            }
        }

        /// <summary>
        /// 添加待办事项
        /// </summary>
        async void Addtodo(ToDoDto model)
        {
            DialogParameters param = new DialogParameters();

            if (model != null)
                param.Add("Value", model);

            var dialogres = await dialog.ShowDialog("AddTodoView", param);

            var newtodo = dialogres.Parameters.GetValue<ToDoDto>("Value");

            if (newtodo == null || string.IsNullOrEmpty(newtodo.Title) || (string.IsNullOrEmpty(newtodo.Content)))
                    return;

            if (dialogres.Result == ButtonResult.OK)
            {
                try
                {


                    if (newtodo.Id > 0)
                    {
                        var updres = await toDoService.UpdateAsync(newtodo);
                        if (updres.Status)
                        {
                            var todo = Summary.TodoList.FirstOrDefault(x=>x.Id.Equals(newtodo.Id));
                            //更新信息
                            todo.Content = newtodo.Content;
                            todo.Title = newtodo.Title;
                            todo.Status = newtodo.Status;
                        }
                    }
                    else
                    {
                        //添加内容 

                        //更新数据库数据
                        var addres  = await toDoService.AddAsync(newtodo);

                        //更新UI数据
                        if (addres.Status)
                        {
                            Summary.TodoList.Add(addres.Result);
                        }
                    }
                }
           
            catch 
            {


            }
            finally
            {
                UpdateLoding(false);
            }
            }

            // 从数据库更新信息
            UpdateData();
        }

        /// <summary>
        /// 添加备忘录
        /// </summary>
        async void Addmemo(MemoDto model)
        {
            DialogParameters param = new DialogParameters();

            if (model != null)
                param.Add("Value", model);

            var dialogres = await dialog.ShowDialog("AddMemoView", param);

            

            if (dialogres.Result == ButtonResult.OK)
            {
                try
                {
                    var newmemo = dialogres.Parameters.GetValue<MemoDto>("Value");

                    if (newmemo != null && string.IsNullOrWhiteSpace(newmemo.Content) && string.IsNullOrWhiteSpace(newmemo.Title))
                        return;

                        if (newmemo.Id > 0)
                    {
                        var updres = await memoService.UpdateAsync(newmemo);
                        if (updres.Status)
                        {
                            //var memo = MemoDtos.FindFirst(predicate: x => x.Id == newmemo.Id);
                            var memo = Summary.MemoList.FirstOrDefault( x => x.Id.Equals( newmemo.Id));
                            //更新信息
                            memo.Content = newmemo.Content;
                            memo.Title = newmemo.Title;
                        }
                    }
                    else
                    {
                        //添加内容
                        
                        
                            var addres = await memoService.AddAsync(newmemo);

                            //更新UI数据
                            if (addres.Status)
                            {
                                Summary.MemoList.Add(addres.Result);
                            }
                        
                    }
                }

                catch
                {


                }
                finally
                {
                    UpdateLoding(false);
                }
            }

            // 从数据库更新信息
            UpdateData();
        }

        #endregion

        #region 其它方法
        /// <summary>
        /// 更新首页所有信息
        /// </summary>
        private async void UpdateData()
        {
            UpdateLoding(true);

            var summaryResult = await summService.GetAllInfo(new SummaryParameter() { PageIndex = 0, PageSize = 1000 });

            if (summaryResult.Status)
            {
                Summary = summaryResult.Result;
                Refresh();
            }

            UpdateLoding(false);
        }
        #endregion

        #region 启动项相关
        void CreatBars()
        {
            Title = "您好,2022";
            TaskBars = new ObservableCollection<TaskBar>();
            TaskBars.Add(new TaskBar { Icon = "CalendarBlankOutline", Title = "汇总", Color = "#FF00FF00", Content = "27", Target = "" });
            TaskBars.Add(new TaskBar { Icon = "CalendarMultipleCheck", Title = "已完成", Color = "#6B238E", Content = "24", Target = "" });
            TaskBars.Add(new TaskBar { Icon = "ChartLine", Title = "完成比例", Color = "#32CD99", Content = "100%", Target = "" });
            TaskBars.Add(new TaskBar { Icon = "CheckboxMarked", Title = "备忘录", Color = "#5959AB", Content = "13", Target = "" });
        }



        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            UpdateData();

            base.OnNavigatedTo(navigationContext);
        }

        void Refresh()
        {
            TaskBars[0].Content = summary.Sum.ToString();
            TaskBars[1].Content = summary.CompeleteCnt.ToString();
            TaskBars[2].Content = summary.CompeleteRatio;
            TaskBars[3].Content = summary.MemoCnt.ToString();
        }


        #endregion


        public IndexViewModel(IContainerProvider provider,
            IDialogHostService dialog) : base(provider)
        {
            //实例化接口
            this.toDoService= provider.Resolve<ITodoService>();
            this.memoService = provider.Resolve<IMemoService>();
            this.summService= provider.Resolve<ISummeryService>();

            //初始化命令
            EditMemoCmd = new DelegateCommand<MemoDto>(Addmemo);
            EditTodoCmd = new DelegateCommand<ToDoDto>(Addtodo);
            ToDoCompltedCommand = new DelegateCommand<ToDoDto>(Compete);
            ExecuteCommand = new DelegateCommand<string>(Execute);

            this.dialog = dialog;

            CreatBars();
        }
    }
}

Je suppose que tu aimes

Origine blog.csdn.net/xinzhiya001/article/details/131994085
conseillé
Classement