WPF实战学习笔记19-备忘录添加功能

文章目录

备忘录添加功能

由于todoview 和 memoview的相似度很高,可复制todoview 的代码。

memoviewmodel.cs

c# 复制代码
using Mytodo.Common.Models;
using Mytodo.Service;
using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using MyToDo.Share.Models;
using System.Threading.Tasks;
using Prism.Regions;
using System.Windows;

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

            /// <summary>
            /// 展开侧边栏
            /// </summary>
            public DelegateCommand OpenRightContentCmd { set; get; }

        /// <summary>
        /// 打开选择的项
        /// </summary>
        public DelegateCommand<MemoDto> SelectedCommand { get; set; }

        /// <summary>
        /// 添加、编辑 项
        /// </summary>
        public DelegateCommand<string> ExecuteCommand { get; set; }

        /// <summary>
        /// 删除项
        /// </summary>
        public DelegateCommand<MemoDto> DeleteCommand { get; set; }

        #endregion

            #region 属性定义


            /// <summary>
            /// 项目状态
            /// </summary>
            public int SelectIndex
        {
            get { return selectIndex; }
            set { selectIndex = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 当前选中项
        /// </summary>
        public MemoDto? CurrDto
        {
            get { return currDto; }
            set { currDto = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 指示侧边栏是否展开
        /// </summary>
        public bool IsRightOpen
        {
            get { return isRightOpen; }
            set { isRightOpen = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// todo集合
        /// </summary>
        public ObservableCollection<MemoDto>? MemoDtos
        {
            get { return memoDtos; }
            set { memoDtos = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 右侧侧边栏标题
        /// </summary>
        public string RightContentTitle
        {
            get { return rightContentTitle; }
            set { rightContentTitle = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 要搜索的字符串
        /// </summary>
        public string SearchString
        {
            get { return search; }
            set { search = value; RaisePropertyChanged(); }
        }

        #endregion

            #region 重要字段定义

            private readonly IMemoService service;

        #endregion

            #region 字段定义
            private int selectIndex;
        private MemoDto currDto;
        private bool isRightOpen;
        private ObservableCollection<MemoDto>? memoDtos;
        private string rightContentTitle;
        private string search;



        #endregion

            #region 命令方法


            /// <summary>
            /// 删除指定项
            /// </summary>
            /// <param name="dto"></param>
            async private void DeleteItem(MemoDto dto)
        {
            var delres = await service.DeleteAsync(dto.Id);

            if (delres.Status)
            {
                var model = MemoDtos.FirstOrDefault(t => t.Id.Equals(dto.Id));
                MemoDtos.Remove(dto);
            }
        }


        private void ExceuteCmd(string obj)
        {
            switch (obj)
            {
                case "添加":
                    Add(); break;
                case "查询":
                    Query(); break;
                case "保存":
                    Save(); break;
            }
        }


        /// <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) //如果添加成功
                    {
                        MemoDtos.Add(add_res.Result);
                    }
                    else
                    {
                        MessageBox.Show("添加失败");

                    }

                }
            }
            catch
            {

            }
            finally
            {
                IsRightOpen = false;
                //卸载数据加载窗体
                UpdateLoding(false);
            }
        }


        /// <summary>
        /// 打开待办事项弹窗
        /// </summary>
        void Add()
        {
            CurrDto = new MemoDto();
            IsRightOpen = true;
        }

        private void Query()
        {
            GetDataAsync();
        }



        /// <summary>
        /// 根据条件更新数据
        /// </summary>
        async void UpdateDataAsync()
        {

            var memoResult = await service.GetAllAsync(new MyToDo.Share.Parameters.QueryParameter { PageIndex = 0, PageSize = 100, Search = SearchString });

            if (memoResult.Status)
            {
                MemoDtos.Clear();
                foreach (var item in memoResult.Result.Items)
                    MemoDtos.Add(item);
            }
        }



        /// <summary>
        /// 获取所有数据
        /// </summary>
        async void GetDataAsync()
        {
            //调用数据加载页面
            UpdateLoding(true);

            //更新数据
            UpdateDataAsync();

            //卸载数据加载页面
            UpdateLoding(false);
        }


        /// <summary>
        /// 弹出详细信息
        /// </summary>
        /// <param name="obj"></param>
        private async void Selected(MemoDto obj)
        {
            var todores = await service.GetFirstOfDefaultAsync(obj.Id);
            if (todores.Status)
            {
                CurrDto = todores.Result;
                IsRightOpen = true;
                RightContentTitle = "我的待办";
            }
        }

        #endregion

            public MemoViewModel(IMemoService service, IContainerProvider provider) : base(provider)
        {
            //初始化对象
            MemoDtos = new ObservableCollection<MemoDto>();
            RightContentTitle = "添加备忘率";

            //初始化命令
            SelectedCommand = new DelegateCommand<MemoDto>(Selected);
            OpenRightContentCmd = new DelegateCommand(Add);
            ExecuteCommand = new DelegateCommand<string>(ExceuteCmd);
            DeleteCommand = new DelegateCommand<MemoDto>(DeleteItem);

            this.service = service;
        }



        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            GetDataAsync();
        }

    }
}

memo.view

xaml 复制代码
<UserControl
    x:Class="Mytodo.Views.MemoView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cv="clr-namespace:Mytodo.Common.Converters"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    xmlns:local="clr-namespace:Mytodo.Views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:md="http://materialdesigninxaml.net/winfx/xaml/themes"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <UserControl.Resources>
        <ResourceDictionary>
            <cv:IntToVisibilityConveter x:Key="IntToVisility" />
        </ResourceDictionary>
    </UserControl.Resources>
    <md:DialogHost>
        <md:DrawerHost IsRightDrawerOpen="{Binding IsRightOpen}">
            <md:DrawerHost.RightDrawerContent>
                <DockPanel
                    MinWidth="200"
                    MaxWidth="240"
                    Margin="2"
                    LastChildFill="False">
                    <TextBlock
                        Margin="10"
                        DockPanel.Dock="Top"
                        FontFamily="微软雅黑"
                        FontSize="20"
                        FontWeight="Bold"
                        Text="{Binding RightContentTitle}" />

                    <StackPanel
                        Margin="10"
                        DockPanel.Dock="Top"
                        Orientation="Horizontal">
                        <TextBlock
                            Margin="5"
                            VerticalAlignment="Center"
                            FontFamily="微软雅黑"
                            FontSize="14"
                            Text="状态" />
                    </StackPanel>
                    <TextBox
                        Margin="10"
                        md:HintAssist.Hint="备忘录事项标题"
                        DockPanel.Dock="Top"
                        FontFamily="微软雅黑"
                        FontSize="12"
                        Text="{Binding CurrDto.Title}" />
                    <TextBox
                        MinHeight="50"
                        Margin="10"
                        md:HintAssist.Hint="备忘录事项内容"
                        DockPanel.Dock="Top"
                        FontFamily="微软雅黑"
                        FontSize="12"
                        Text="{Binding CurrDto.Content}"
                        TextWrapping="Wrap" />
                    <Button
                        Margin="10,5"
                        HorizontalAlignment="Center"
                        Command="{Binding ExecuteCommand}"
                        CommandParameter="保存"
                        Content="保存"
                        DockPanel.Dock="Top" />
                </DockPanel>
            </md:DrawerHost.RightDrawerContent>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition />
                </Grid.RowDefinitions>

                <StackPanel Margin="15,10" Orientation="Horizontal">
                    <TextBox
                        Width="200"
                        md:HintAssist.Hint="查找备忘录中"
                        md:TextFieldAssist.HasClearButton="True"
                        FontFamily="微软雅黑"
                        FontSize="14"
                        Text="{Binding SearchString, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                        <TextBox.InputBindings>
                            <KeyBinding
                                Key="Enter"
                                Command="{Binding ExecuteCommand}"
                                CommandParameter="查询" />
                        </TextBox.InputBindings>
                    </TextBox>

                </StackPanel>
                <Button
                    Margin="10,0"
                    HorizontalAlignment="Right"
                    Command="{Binding OpenRightContentCmd}"
                    Content="+ 添加到备忘"
                    FontFamily="微软雅黑"
                    FontSize="14" />
                <StackPanel
                    Grid.Row="1"
                    VerticalAlignment="Center"
                    Visibility="{Binding MemoDtos.Count, Converter={StaticResource IntToVisility}}">
                    <md:PackIcon
                        Width="120"
                        Height="120"
                        HorizontalAlignment="Center"
                        Kind="ClipboardText" />
                    <TextBlock
                        Margin="0,10"
                        HorizontalAlignment="Center"
                        FontSize="18"
                        Text="尝试添加一些待办事项,以便在此处查看它们。" />
                </StackPanel>
                <ItemsControl
                    Grid.Row="1"
                    Margin="10"
                    ItemsSource="{Binding MemoDtos}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapPanel />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Border MinWidth="200" Margin="10">
                                <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">
                                        <TextBlock
                                            Margin="10,10"
                                            FontFamily="黑体"
                                            FontSize="14"
                                            Text="{Binding Title}" />
                                        <md:PopupBox
                                            Margin="5"
                                            Panel.ZIndex="1"
                                            DockPanel.Dock="Right">
                                            <Button
                                                Panel.ZIndex="2"
                                                Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}"
                                                CommandParameter="{Binding}"
                                                Content="删除" />
                                        </md:PopupBox>
                                    </DockPanel>
                                    <TextBlock
                                        Grid.Row="1"
                                        Margin="10,5"
                                        FontFamily="黑体"
                                        FontSize="12"
                                        Opacity="0.7"
                                        Text="{Binding Content}" />
                                    <Canvas Grid.RowSpan="2" ClipToBounds="True">
                                        <Border
                                            Canvas.Top="10"
                                            Canvas.Right="-50"
                                            Width="120"
                                            Height="120"
                                            Background="#FFFFFF"
                                            CornerRadius="100"
                                            Opacity="0.1" />
                                        <Border
                                            Canvas.Top="80"
                                            Canvas.Right="-30"
                                            Width="120"
                                            Height="120"
                                            Background="#FFFFFF"
                                            CornerRadius="100"
                                            Opacity="0.1" />
                                    </Canvas>
                                    <Border
                                        Grid.RowSpan="2"
                                        Background="#ffffcc"
                                        CornerRadius="5"
                                        Opacity="0.3" />
                                </Grid>
                            </Border>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Grid>
        </md:DrawerHost>
    </md:DialogHost>
</UserControl>

修改控制器

c# 复制代码
public async Task<ApiReponse> Delete(int todoid) => await service.DeleteApublic async Task<ApiReponse> Delete(int todoid) =>
相关推荐
楚疏笃6 分钟前
鸿蒙学习统一上架与多端分发-应用分发(2)
学习·华为·harmonyos
谢白羽14 分钟前
CUDA补充笔记
笔记
醉陌离17 分钟前
渗透测试笔记—shodan(7完结)
笔记
XR-AI-JK1 小时前
UE5肉鸽游戏教程学习
学习·游戏·ue5·ue4·新手学习·游戏教程·ue教程
咔叽布吉1 小时前
【前端学习笔记】ES6 新特性
前端·笔记·学习
超越✔1 小时前
学习内容分享
笔记·学习·面试
Lostgreen1 小时前
SQL on Hadoop
数据库·hadoop·笔记·分布式·sql·学习
坚硬果壳_2 小时前
《硬件架构的艺术》笔记(八):消抖技术
笔记·硬件架构
八年。。2 小时前
MATLAB 中有关figure图表绘制函数设计(论文中常用)
开发语言·笔记·学习·matlab