WPF实战学习笔记24-首页编辑与完成

首页编辑与完成

  • indexview添加Listbox控件的鼠标双击行为
    • 添加todo、memo的编辑命令
    • indexviewmodel添加对应的更新事件处理
  • 添加ToggleButton与后台的绑定
    • 将ToggleButton的ischeck绑定到status属性
    • 添加bool int 转换器
    • 添加完成命令
    • 添加完成功能函数

Listbox添加行为

给行为添加命令空间

文件:Mytodo.Views.IndexView.cs

    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

添加行为事件

文件:Mytodo.Views.IndexView.cs


    
        
    


    
        
    

后台添加对应的命令,并初始化

文件:Mytodo.Views.IndexViewmodel.cs

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

/// 
/// 命令:编辑待办
/// 
public DelegateCommand EditTodoCmd { get; private set; }
//初始化命令
EditMemoCmd = new DelegateCommand(Addmemo);
EditTodoCmd = new DelegateCommand(Addtodo);

添加命令方法

文件:Mytodo.Views.IndexViewmodel.cs

/// 
/// 添加待办事项
/// 
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("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 = TodoDtos.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)
                {
                    TodoDtos.Add(addres.Result);
                }
            }
        }

        catch 
        {


        }
        finally
        {
            UpdateLoding(false);
        }
    }

}

/// 
/// 添加备忘录
/// 
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("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 = MemoDtos.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)
                {
                    MemoDtos.Add(addres.Result);
                }

            }
        }

        catch
        {


        }
        finally
        {
            UpdateLoding(false);
        }
    }
}

添加ToggleButton绑定与check事件

添加转换器

添加文件:Mytodo.Common.Converters.BoolInt_TConverter.cs

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace Mytodo.Common.Converters
{
    public  class BoolInt_TConverter : IValueConverter
    {
        /// 
        /// int to bool
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value!=null&&int.TryParse(value.ToString(),out int result))
            {
                if(result==0)
                    return true;
                else
                    return false;
            }
            return false;
        }


        /// 
        /// bool to int 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && bool.TryParse(value.ToString(), out bool result))
            {
                if (result)
                    return 0;
                else
                    return 1;
            }
            return false;
        }
    }
}

添加转换器,添加命令

修改文件:Mytodo.Views.IndexView.xaml

  1. 添加命名空间
    xmlns:cv="clr-namespace:Mytodo.Common.Converters"
  1. 添加资源

        
            
                
            
        
    
  2. 绑定命令,添加转换器

    
    
    
  3. 定义命令,并初始化

    /// 
    /// Todo完成命令
    /// 
    public DelegateCommand ToDoCompltedCommand { get; set; }
    public IndexViewModel(IContainerProvider provider,
                          IDialogHostService dialog) : base(provider)
    {
        //实例化接口
        this.toDoService= provider.Resolve();
        this.memoService = provider.Resolve();
    
        //实例化对象
        MemoDtos = new ObservableCollection();
        TodoDtos = new ObservableCollection();
    
        //初始化命令
        EditMemoCmd = new DelegateCommand(Addmemo);
        EditTodoCmd = new DelegateCommand(Addtodo);
        ToDoCompltedCommand = new DelegateCommand(Compete);
        ExecuteCommand = new DelegateCommand(Execute);
    
        this.dialog = dialog;
    
        CreatBars();
    }
    
  4. 初始化命令操作函数

    /// 
    /// togglebutoon 的命令
    /// 
    /// 
    /// 
    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 = TodoDtos.FirstOrDefault(x => x.Id.Equals(dto.Id));
            //更新信息
            todo.Status = dto.Status;
        }
    }
    

修改相关bug

修改Mytodo.ViewModels.cs

using Mytodo.Common.Models;
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;

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


        /// 
        /// Todo完成命令
        /// 
        public DelegateCommand ToDoCompltedCommand { get; set; }
        public DelegateCommand ExecuteCommand { get; set; }

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

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


        #endregion

        #region 定义属性
        public string Title { get; set; }

        public ObservableCollection MemoDtos
        {
            get { return memoDtos; }
            set { memoDtos = value; RaisePropertyChanged(); }
        }

        public ObservableCollection TodoDtos
        {
            get { return todoDtos; }
            set { todoDtos = value; RaisePropertyChanged(); }
        }

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

        #region 定义重要命令

        #endregion

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

        #region 定义普通字段
        private ObservableCollection taskBars;
        private ObservableCollection todoDtos;
        private ObservableCollection memoDtos;
        #endregion

        #region 命令相关方法

        /// 
        /// togglebutoon 的命令
        /// 
        /// 
        /// 
        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 = TodoDtos.FirstOrDefault(x => x.Id.Equals(dto.Id));
                //更新信息
                todo.Status = dto.Status;
            }
        }

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

        /// 
        /// 添加待办事项
        /// 
        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("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 = TodoDtos.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)
                        {
                            TodoDtos.Add(addres.Result);
                        }
                    }
                }
           
            catch 
            {


            }
            finally
            {
                UpdateLoding(false);
            }
            }

        }

        /// 
        /// 添加备忘录
        /// 
        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("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 = MemoDtos.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)
                            {
                                MemoDtos.Add(addres.Result);
                            }
                        
                    }
                }

                catch
                {


                }
                finally
                {
                    UpdateLoding(false);
                }
            }
        }

        #endregion

        #region 其它方法

        #endregion

        #region 启动项相关
        void CreatBars()
        {
            Title = "您好,2022";
            TaskBars = new ObservableCollection();
            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 = "" });
        }
        #endregion


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

            //实例化对象
            MemoDtos = new ObservableCollection();
            TodoDtos = new ObservableCollection();

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

            this.dialog = dialog;

            CreatBars();
        }
    }
}

修改Mytodo.AddMemoViewModel.cs

using MaterialDesignThemes.Wpf;
using Mytodo.Dialog;
using MyToDo.Share.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.ViewModels.Dialogs
{
    internal class AddMemoViewModel : BindableBase, IDialogHostAware
    {
        public AddMemoViewModel()
        {
            SaveCommand = new DelegateCommand(Save);
            CancelCommand = new DelegateCommand(Cancel);
        }

        private MemoDto model;

        public MemoDto Model
        {
            get { return model; }
            set { model = value; RaisePropertyChanged(); }
        }

        private void Cancel()
        {
            if (DialogHost.IsDialogOpen(DialogHostName))
                DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.No));
        }

        private void Save()
        {

            if (DialogHost.IsDialogOpen(DialogHostName))
            {
                //确定时,把编辑的实体返回并且返回OK
                DialogParameters param = new DialogParameters();
                param.Add("Value", Model);
                DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.OK, param));
            }
        }

        public string DialogHostName { get; set; }
        public DelegateCommand SaveCommand { get; set; }
        public DelegateCommand CancelCommand { get; set; }

        public void OnDialogOpend(IDialogParameters parameters)
        {
            if (parameters.ContainsKey("Value"))
            {
                Model = parameters.GetValue("Value");
                if(Model == null) {
                    Model = new MemoDto();
                }c
            }
            else
                Model = new MemoDto();
        }
    }
}

修改Mytodo.AddTodoViewModel.cs

using MaterialDesignThemes.Wpf;
using Mytodo.Dialog;
using MyToDo.Share.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.ViewModels.Dialogs
{
    internal class AddTodoViewModel : BindableBase, IDialogHostAware
    {
        public AddTodoViewModel()
        {
            SaveCommand = new DelegateCommand(Save);
            CancelCommand = new DelegateCommand(Cancel);

        }

        private ToDoDto model;

        /// 
        /// 新增或编辑的实体
        /// 
        public ToDoDto Model
        {
            get { return model; }
            set { model = value; RaisePropertyChanged(); }
        }

        /// 
        /// 取消
        /// 
        private void Cancel()
        {
            if (DialogHost.IsDialogOpen(DialogHostName))
                DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.No)); //取消返回NO告诉操作结束
        }

        /// 
        /// 确定
        /// 
        private void Save()
        {
            if (DialogHost.IsDialogOpen(DialogHostName))
            {
                //确定时,把编辑的实体返回并且返回OK
                DialogParameters param = new DialogParameters();
                param.Add("Value", Model);
                DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.OK, param));
            }
        }

        public string DialogHostName { get; set; }
        public DelegateCommand SaveCommand { get; set; }
        public DelegateCommand CancelCommand { get; set; }

        public void OnDialogOpend(IDialogParameters parameters)
        {
            if (parameters.ContainsKey("Value"))
            {
                Model = parameters.GetValue("Value");
                if (Model == null)
                {
                    Model = new ToDoDto();
                    Model.Status = 1;
                }
            }
            else
            {
                Model = new ToDoDto();
                Model.Status = 1;
            }

        }
    }
}

你可能感兴趣的:(WPF实战学习笔记,wpf,学习,笔记)