WPF实战项目十八(客户端):添加新增、查询、编辑功能

news/2024/5/19 22:25:50 标签: wpf, webapi, .netcore, c#

1、ToDoView.xmal添加引用,添加微软的行为类

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

2、给项目添加行为

<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>

3、ToDoViewModel.cs新建查询SelectedCommand

public DelegateCommand<ToDoDto> SelectedCommand { get;private set; }
        
public ToDoViewModel(IToDoService toDoService, IContainerProvider provider) : base(provider)
        {
            ToDoDtos = new ObservableCollection<ToDoDto>();
            AddCommand = new DelegateCommand(Add);
            SelectedCommand = new DelegateCommand<ToDoDto>(Selected);
            this.toDoService = toDoService;
        }
private async void Selected(ToDoDto obj)
        {
            try
            {
                UpdateLoading(true);
                var todoResult = await toDoService.GetFirstOfDefaultAsync(obj.Id);
                if (todoResult.Status)
                {
                    IsIsRightDrawerOpens = true;
                    CurrentDto = todoResult.Result;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                UpdateLoading(false);
            }

        }

4、新建属性编辑选中/新增时的对象

private ToDoDto currentDto;
        /// <summary>
        /// 编辑选中/新增时的对象
        /// </summary>
        public ToDoDto CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }

5、前台绑定文本标题、内容、状态

                    <StackPanel
                        Margin="20"
                        DockPanel.Dock="Top"
                        Orientation="Horizontal">
                        <TextBlock VerticalAlignment="Center" Text="状态:" />
                        <ComboBox SelectedIndex="{Binding CurrentDto.Status}">
                            <ComboBoxItem>待办</ComboBoxItem>
                            <ComboBoxItem>已完成</ComboBoxItem>
                        </ComboBox>
                    </StackPanel>
                    <TextBox
                        Margin="20,5"
                        md:HintAssist.Hint="请输入待办概要"
                        DockPanel.Dock="Top"
                        Text="{Binding CurrentDto.Title}" />
                    <TextBox
                        MinHeight="100"
                        Margin="20,10"
                        md:HintAssist.Hint="请输入待办事项内容"
                        DockPanel.Dock="Top"
                        Text="{Binding CurrentDto.Content}" />

6、F5运行项目,点击待办事项能在右侧显示信息

7、绑定搜索输入框,首先定义一个属性,前台绑定输入框的值Search,给输入框添加回车事件

        private string search;
        /// <summary>
        /// 搜索条件
        /// </summary>
        public string Search
        {
            get { return search; }
            set { search = value; RaisePropertyChanged(); }
        }
<TextBox
                        Width="250"
                        md:HintAssist.Hint="查找待办事项..."
                        md:TextFieldAssist.HasClearButton="True"
                        Text="{Binding Search, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                        <TextBox.InputBindings>
                            <KeyBinding Key="Enter" Command="{Binding SearchCommand}" />
                        </TextBox.InputBindings>
                    </TextBox>

8、SearchCommand搜索事件可以和上面AddCommand合并到一起,【添加待办】按钮设置事件:ExecuteCommand,参数设置="新增",查找框设置成ExecuteCommand,参数设置="查询"

public DelegateCommand<string> ExecuteCommand { get; private set; }
        
public ToDoViewModel(IToDoService toDoService, IContainerProvider provider) : base(provider)
        {
            ToDoDtos = new ObservableCollection<ToDoDto>();
            ExecuteCommand = new DelegateCommand<string>(Execute);
            SelectedCommand = new DelegateCommand<ToDoDto>(Selected);
            this.toDoService = toDoService;
        }
                <Button
                    Margin="10,0"
                    HorizontalAlignment="Right"
                    Command="{Binding ExecuteCommand}"
                    CommandParameter="新增"
                    Content="+ 添加待办" />
<TextBox
                        Width="250"
                        md:HintAssist.Hint="查找待办事项..."
                        md:TextFieldAssist.HasClearButton="True"
                        Text="{Binding Search, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                        <TextBox.InputBindings>
                            <KeyBinding
                                Key="Enter"
                                Command="{Binding ExecuteCommand}"
                                CommandParameter="查询" />
                        </TextBox.InputBindings>
                    </TextBox>

9、获取数据的函数里面把Search属性传进去

/// <summary>
        /// 获取数据
        /// </summary>
        private async void GetDataAsync()
        {
            UpdateLoading(true);

            var todoResult = await toDoService.GetAllPageListAsync(new WPFProjectShared.Parameters.QueryParameter
            {
                PageIndex = 0,
                PageSize = 100,
                Search = Search
            });
            if (todoResult.Status)
            {
                toDoDtos.Clear();
                foreach (var item in todoResult.Result.Items)
                {
                    toDoDtos.Add(item);
                }
            }
            UpdateLoading(false);
        }

10、新增Excute方法和Query方法

private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增":Add();
                    break;
                case "查询":Query();
                    break;
            }
        }

        private void Query()
        {
            GetDataAsync();
        }

11、F5运行项目,在搜索框里面查询显示12、【保存】事件,按钮添加绑定事件,修改Excute方法、新增Add方法和Save方法

                    <Button
                        Margin="20,0"
                        Command="{Binding ExecuteCommand}"
                        CommandParameter="保存"
                        Content="添加到待办"
                        DockPanel.Dock="Top" />
        private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增":Add();
                    break;
                case "查询":Query();
                    break;
                case "保存":Save();
                    break;
            }
        }
        /// <summary>
        /// 添加待办
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Add()
        {
            CurrentDto = new ToDoDto();
            IsIsRightDrawerOpens = true;
        }
private async void Save()
        {
            if (string.IsNullOrWhiteSpace(CurrentDto.Title) || string.IsNullOrWhiteSpace(CurrentDto.Content))
            {
                return;
            }
            else
            {
                UpdateLoading(true);
                try
                {
                    if (CurrentDto.Id > 0)//update
                    {
                        var updateResult = await toDoService.UpdateAsync(CurrentDto);
                        if (updateResult.Status)
                        {
                            var todo = ToDoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                            if (todo != null)
                            {
                                todo.Title = CurrentDto.Title;
                                todo.Content = CurrentDto.Content;
                                todo.Status = CurrentDto.Status;
                            }
                        }
                        IsIsRightDrawerOpens = false;
                    }
                    else//add
                    {
                        var addResult = await toDoService.AddAsync(CurrentDto);
                        if (addResult.Status)
                        {
                            ToDoDtos.Add(addResult.Result);
                            IsIsRightDrawerOpens = false;
                        }
                    }
                }
                catch (Exception)
                {

                    throw;
                }finally { UpdateLoading(false); }

            }

        }

修改API中TodoController的代码

        [HttpPost]
        public async Task<ApiResponse> Update(TodoDto toDo)
        {
            return await toDoService.UpdateEntityAsync(toDo);
        }

13、F5运行项目,测试修改待办

保存的时候报错:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-40d7073ee1cf77c77875996f55f65034-4888403c8bef54ca-00","errors":{"toDo":["The toDo field is required."],"$.Status":["The JSON value could not be converted to System.String. Path: $.Status | LineNumber: 0 | BytePositionInLine: 59."]}}

后来发现是实体类引用错误导致,重新引用WPFProjectShared.Dtos.TodoDto,

另外一个报错:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-25e255d827e2947f869ccba30a1714e4-b2423a142252e535-00","errors":{"$":["'-' is invalid within a number, immediately after a sign character ('+' or '-'). Expected a digit ('0'-'9'). Path: $ | LineNumber: 0 | BytePositionInLine: 1."],"toDo":["The toDo field is required."]}}

修改请求参数的格式application/json

ToDoView.xmal完整代码:

<UserControl
    x:Class="WPFProject.Views.ToDoView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    xmlns:local="clr-namespace:WPFProject.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">
    <md:DialogHost>
        <md:DrawerHost IsRightDrawerOpen="{Binding IsIsRightDrawerOpens}">
            <md:DrawerHost.RightDrawerContent>
                <DockPanel Width="300" LastChildFill="False">
                    <TextBlock
                        Padding="20,10"
                        DockPanel.Dock="Top"
                        FontSize="20"
                        FontWeight="Bold"
                        Text="添加待办" />
                    <StackPanel
                        Margin="20"
                        DockPanel.Dock="Top"
                        Orientation="Horizontal">
                        <TextBlock VerticalAlignment="Center" Text="状态:" />
                        <ComboBox SelectedIndex="{Binding CurrentDto.Status}">
                            <ComboBoxItem>待办</ComboBoxItem>
                            <ComboBoxItem>已完成</ComboBoxItem>
                        </ComboBox>
                    </StackPanel>
                    <TextBox
                        Margin="20,5"
                        md:HintAssist.Hint="请输入待办概要"
                        DockPanel.Dock="Top"
                        Text="{Binding CurrentDto.Title}" />
                    <TextBox
                        MinHeight="100"
                        Margin="20,10"
                        md:HintAssist.Hint="请输入待办事项内容"
                        DockPanel.Dock="Top"
                        Text="{Binding CurrentDto.Content}" />
                    <Button
                        Margin="20,0"
                        Command="{Binding ExecuteCommand}"
                        CommandParameter="保存"
                        Content="添加到待办"
                        DockPanel.Dock="Top" />
                </DockPanel>
            </md:DrawerHost.RightDrawerContent>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <StackPanel
                    Margin="15,15,0,0"
                    VerticalAlignment="Center"
                    Orientation="Horizontal">
                    <TextBox
                        Width="250"
                        md:HintAssist.Hint="查找待办事项..."
                        md:TextFieldAssist.HasClearButton="True"
                        Text="{Binding Search, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                        <TextBox.InputBindings>
                            <KeyBinding
                                Key="Enter"
                                Command="{Binding ExecuteCommand}"
                                CommandParameter="查询" />
                        </TextBox.InputBindings>
                    </TextBox>
                    <TextBlock
                        Margin="10,0,5,0"
                        VerticalAlignment="Center"
                        Text="筛选:" />
                    <ComboBox Width="80" SelectedIndex="0">
                        <ComboBoxItem>全部</ComboBoxItem>
                        <ComboBoxItem>待办</ComboBoxItem>
                        <ComboBoxItem>已完成</ComboBoxItem>
                    </ComboBox>
                </StackPanel>
                <Button
                    Margin="10,0"
                    HorizontalAlignment="Right"
                    Command="{Binding ExecuteCommand}"
                    CommandParameter="新增"
                    Content="+ 添加待办" />

                <ScrollViewer Grid.Row="1">
                    <ItemsControl
                        Grid.Row="1"
                        Margin="0,20"
                        HorizontalAlignment="Center"
                        ItemsSource="{Binding ToDoDtos}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel />
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <md:TransitioningContent OpeningEffect="{md:TransitionEffect Kind=ExpandIn}">
                                    <Grid
                                        Width="220"
                                        MinHeight="180"
                                        MaxHeight="250"
                                        Margin="8">
                                        <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>
                                        <md:PopupBox HorizontalAlignment="Right" Panel.ZIndex="1">
                                            <Button Content="删除" />
                                        </md:PopupBox>
                                        <Border
                                            Grid.RowSpan="2"
                                            Background="#10B136"
                                            CornerRadius="5" />

                                        <TextBlock
                                            Padding="10,5"
                                            FontWeight="Bold"
                                            Text="{Binding Title}" />
                                        <TextBlock
                                            Grid.Row="1"
                                            Padding="10,5"
                                            Text="{Binding Content}" />
                                        <Canvas Grid.RowSpan="2" ClipToBounds="True">
                                            <!--  切割  -->
                                            <Border
                                                Canvas.Top="20"
                                                Canvas.Right="-80"
                                                Width="120"
                                                Height="120"
                                                Background="#FFFFFF"
                                                CornerRadius="60"
                                                Opacity="0.1" />
                                            <Border
                                                Canvas.Top="100"
                                                Canvas.Right="-40"
                                                Width="140"
                                                Height="140"
                                                Background="#FFFFFF"
                                                CornerRadius="70"
                                                Opacity="0.1" />
                                        </Canvas>
                                    </Grid>
                                </md:TransitioningContent>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </ScrollViewer>
            </Grid>
        </md:DrawerHost>
    </md:DialogHost>
</UserControl>

 ToDoViewModel.cs完整代码

using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFProject.Common.Models;
using WPFProject.Service;
using WPFProjectShared.Dtos;

namespace WPFProject.ViewModels
{
    public class ToDoViewModel : NavigationViewModel
    {
        private readonly IToDoService toDoService;
        public ToDoViewModel(IToDoService toDoService, IContainerProvider provider) : base(provider)
        {
            ToDoDtos = new ObservableCollection<TodoDto>();
            ExecuteCommand = new DelegateCommand<string>(Execute);
            SelectedCommand = new DelegateCommand<TodoDto>(Selected);
            this.toDoService = toDoService;
        }

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增":Add();
                    break;
                case "查询":Query();
                    break;
                case "保存":Save();
                    break;
            }
        }

        private async void Save()
        {
            if (string.IsNullOrWhiteSpace(CurrentDto.Title) || string.IsNullOrWhiteSpace(CurrentDto.Content))
            {
                return;
            }
            else
            {
                UpdateLoading(true);
                try
                {
                    if (CurrentDto.Id > 0)//update
                    {
                        var updateResult = await toDoService.UpdateAsync(CurrentDto);
                        if (updateResult.Status)
                        {
                            var todo = ToDoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                            if (todo != null)
                            {
                                todo.Title = CurrentDto.Title;
                                todo.Content = CurrentDto.Content;
                                todo.Status = CurrentDto.Status;
                            }
                        }
                        IsIsRightDrawerOpens = false;
                    }
                    else//add
                    {
                        var addResult = await toDoService.AddAsync(CurrentDto);
                        if (addResult.Status)
                        {
                            ToDoDtos.Add(addResult.Result);
                            IsIsRightDrawerOpens = false;
                        }
                    }
                }
                catch (Exception)
                {

                    throw;
                }finally { UpdateLoading(false); }

            }

        }

        private void Query()
        {
            GetDataAsync();
        }


        /// <summary>
        /// 添加待办
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Add()
        {
            CurrentDto = new TodoDto();
            IsIsRightDrawerOpens = true;
        }
        private async void Selected(TodoDto obj)
        {
            try
            {
                UpdateLoading(true);
                var todoResult = await toDoService.GetFirstOfDefaultAsync(obj.Id);
                if (todoResult.Status)
                {
                    IsIsRightDrawerOpens = true;
                    CurrentDto = todoResult.Result;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                UpdateLoading(false);
            }

        }

        public DelegateCommand<string> ExecuteCommand { get; private set; }
        public DelegateCommand<TodoDto> SelectedCommand { get;private set; }
        private bool isIsRightDrawerOpens;
        /// <summary>
        /// 右侧新增窗口是否打开
        /// </summary>
        public bool IsIsRightDrawerOpens
        {
            get { return isIsRightDrawerOpens; }
            set { isIsRightDrawerOpens = value; RaisePropertyChanged(); }
        }
        private TodoDto currentDto;
        /// <summary>
        /// 编辑选中/新增时的对象
        /// </summary>
        public TodoDto CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }
        private string search;
        /// <summary>
        /// 搜索条件
        /// </summary>
        public string Search
        {
            get { return search; }
            set { search = value; RaisePropertyChanged(); }
        }


        private ObservableCollection<TodoDto> toDoDtos;
        public ObservableCollection<TodoDto> ToDoDtos
        {
            get { return toDoDtos; }
            set { toDoDtos = value; }
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        private async void GetDataAsync()
        {
            UpdateLoading(true);

            var todoResult = await toDoService.GetAllPageListAsync(new WPFProjectShared.Parameters.QueryParameter
            {
                PageIndex = 0,
                PageSize = 100,
                Search = Search
            });
            if (todoResult.Status)
            {
                toDoDtos.Clear();
                foreach (var item in todoResult.Result.Items)
                {
                    toDoDtos.Add(item);
                }
            }
            UpdateLoading(false);
        }


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

备忘录也相应修改,完整代码如下:

MemoView.xmal

<UserControl
    x:Class="WPFProject.Views.MemoView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    xmlns:local="clr-namespace:WPFProject.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">
    <md:DialogHost>
        <md:DrawerHost IsRightDrawerOpen="{Binding IsIsRightDrawerOpens}">
            <md:DrawerHost.RightDrawerContent>
                <DockPanel Width="300" LastChildFill="False">
                    <TextBlock
                        Padding="20,10"
                        DockPanel.Dock="Top"
                        FontSize="20"
                        FontWeight="Bold"
                        Text="添加备忘录" />
                    <TextBox
                        Margin="20,5"
                        md:HintAssist.Hint="请输入备忘录概要"
                        DockPanel.Dock="Top"
                        Text="{Binding CurrentDto.Title}" />
                    <TextBox
                        MinHeight="100"
                        Margin="20,10"
                        md:HintAssist.Hint="请输入备忘录内容"
                        DockPanel.Dock="Top"
                        Text="{Binding CurrentDto.Content}" />
                    <Button
                        Margin="20,0"
                        Command="{Binding ExecuteCommand}"
                        CommandParameter="保存"
                        Content="添加到备忘录"
                        DockPanel.Dock="Top" />
                </DockPanel>
            </md:DrawerHost.RightDrawerContent>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <StackPanel
                    Margin="15,15,0,0"
                    VerticalAlignment="Center"
                    Orientation="Horizontal">
                    <TextBox
                        Width="250"
                        md:HintAssist.Hint="查找备忘录..."
                        md:TextFieldAssist.HasClearButton="True"
                        Text="{Binding Search, 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 ExecuteCommand}"
                    CommandParameter="新增"
                    Content="+ 添加备忘录" />
                <ScrollViewer Grid.Row="1">
                    <ItemsControl
                        Margin="0,20"
                        HorizontalAlignment="Center"
                        ItemsSource="{Binding MemoDtos}">
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <WrapPanel />
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <md:TransitioningContent OpeningEffect="{md:TransitionEffect Kind=ExpandIn}">
                                    <Grid
                                        Width="220"
                                        MinHeight="180"
                                        MaxHeight="250"
                                        Margin="8">
                                        <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>
                                        <md:PopupBox HorizontalAlignment="Right" Panel.ZIndex="1">
                                            <Button Content="删除" />
                                        </md:PopupBox>
                                        <Border
                                            Grid.RowSpan="2"
                                            Background="#10B136"
                                            CornerRadius="5" />

                                        <TextBlock
                                            Padding="10,5"
                                            FontWeight="Bold"
                                            Text="{Binding Title}" />
                                        <TextBlock
                                            Grid.Row="1"
                                            Padding="10,5"
                                            Text="{Binding Content}" />
                                        <Canvas Grid.RowSpan="2" ClipToBounds="True">
                                            <!--  切割  -->
                                            <Border
                                                Canvas.Top="20"
                                                Canvas.Right="-80"
                                                Width="120"
                                                Height="120"
                                                Background="#FFFFFF"
                                                CornerRadius="60"
                                                Opacity="0.1" />
                                            <Border
                                                Canvas.Top="100"
                                                Canvas.Right="-40"
                                                Width="140"
                                                Height="140"
                                                Background="#FFFFFF"
                                                CornerRadius="70"
                                                Opacity="0.1" />
                                        </Canvas>
                                    </Grid>
                                </md:TransitioningContent>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </ScrollViewer>
            </Grid>
        </md:DrawerHost>
    </md:DialogHost>
</UserControl>

 MemoViewModel.cs

using Prism.Commands;
using Prism.Ioc;
using Prism.Regions;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using WPFProject.Common.Models;
using WPFProject.Service;
using WPFProjectShared.Dtos;

namespace WPFProject.ViewModels
{
    public class MemoViewModel : NavigationViewModel
    {
        private readonly IMemoService memoService;
        public MemoViewModel(IMemoService memoService, IContainerProvider provider) : base(provider)
        {
            MemoDtos = new ObservableCollection<MemoDto>();
            ExecuteCommand = new DelegateCommand<string>(Execute);
            SelectedCommand = new DelegateCommand<MemoDto>(Selected);
            this.memoService = memoService;
        }

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "新增":
                    Add();
                    break;
                case "查询":
                    Query();
                    break;
                case "保存":
                    Save();
                    break;
            }
        }

        private async void Save()
        {
            if (string.IsNullOrWhiteSpace(CurrentDto.Title) || string.IsNullOrWhiteSpace(CurrentDto.Content))
            {
                return;
            }
            else
            {
                UpdateLoading(true);
                try
                {
                    if (CurrentDto.Id > 0)//update
                    {
                        var updateResult = await memoService.UpdateAsync(CurrentDto);
                        if (updateResult.Status)
                        {
                            var todo = MemoDtos.FirstOrDefault(t => t.Id == CurrentDto.Id);
                            if (todo != null)
                            {
                                todo.Title = CurrentDto.Title;
                                todo.Content = CurrentDto.Content;
                            }
                        }
                        IsIsRightDrawerOpens = false;
                    }
                    else//add
                    {
                        var addResult = await memoService.AddAsync(CurrentDto);
                        if (addResult.Status)
                        {
                            MemoDtos.Add(addResult.Result);
                            IsIsRightDrawerOpens = false;
                        }
                    }
                }
                catch (Exception)
                {

                    throw;
                }
                finally { UpdateLoading(false); }

            }

        }

        private void Query()
        {
            GetDataAsync();
        }

        private async void Selected(MemoDto obj)
        {
            try
            {
                UpdateLoading(true);
                var memoResult = await memoService.GetFirstOfDefaultAsync(obj.Id);
                if (memoResult.Status)
                {
                    IsIsRightDrawerOpens = true;
                    CurrentDto = memoResult.Result;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                UpdateLoading(false);
            }
        }

        private void Add()
        {
            CurrentDto = new MemoDto();
            IsIsRightDrawerOpens = true;
        }

        public DelegateCommand AddCommand { get; private set; }
        public DelegateCommand<MemoDto> SelectedCommand { get; private set; }
        public DelegateCommand<string> ExecuteCommand { get; private set; }
        private bool isIsRightDrawerOpens;

        public bool IsIsRightDrawerOpens
        {
            get { return isIsRightDrawerOpens; }
            set { isIsRightDrawerOpens = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<MemoDto> memoDtos;

        public ObservableCollection<MemoDto> MemoDtos
        {
            get { return memoDtos; }
            set { memoDtos = value; RaisePropertyChanged(); }
        }
        private MemoDto currentDto;
        /// <summary>
        /// 新增/编辑 选中数据
        /// </summary>
        public MemoDto CurrentDto
        {
            get { return currentDto; }
            set { currentDto = value; RaisePropertyChanged(); }
        }
        private string search;
        /// <summary>
        /// 搜索条件
        /// </summary>
        public string Search
        {
            get { return search; }
            set { search = value; RaisePropertyChanged(); }
        }
        private async void GetDataAsync()
        {
            UpdateLoading(true);

            var memoResult = await memoService.GetAllPageListAsync(new WPFProjectShared.Parameters.QueryParameter
            {
                PageIndex = 0,
                PageSize = 100,
                Search = Search
            });
            if (memoResult.Status)
            {
                memoDtos.Clear();
                foreach (var item in memoResult.Result.Items)
                {
                    memoDtos.Add(item);
                }
            }

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


http://www.niftyadmin.cn/n/5227843.html

相关文章

2023/11/30JAVAweb学习

数组json形式 想切换实现类,只需要只在你需要的类上添加 Component 如果在同一层,可以更改扫描范围,但是不推荐这种方法 注入时存在多个同类型bean解决方式

C语言——指针(三)

&#x1f4dd;前言&#xff1a; 上篇文章C语言——指针&#xff08;二&#xff09;中对&#xff1a;指针的运算和指针变量类型对指针使用的影响开展了进一步的探讨&#xff0c;这篇文章我们继续学习一下指针与一维数组之间的关系&#xff1a; 1&#xff0c;对数组名的理解 2&am…

ffmpeg开发 环境配置

ffmpeg开发简图 1 下载ffmpeg开发包 https://ffmpeg.org/download.html 包含三个版本&#xff1a;Static、Shared以及Dev Static --- 包含3个应用程序&#xff1a;ffmpeg.exe , ffplay.exe , ffprobe.exe&#xff0c;体积都很大&#xff0c;相关的DLL已经被编译到exe里面去…

【场景测试用例】二维码

测试思路&#xff1a; UI 不同设备&#xff0c;不同浏览器下的外观和布局一致用户友好性 二维码足够清晰且大小合适是否有错误提示是否有扫描成功/失败提示启动&#xff0c;扫描过程 功能 验证识别功能 二维码完整且有效二维码失效二维码不完整/过于模糊空白二维码测试不同大小…

使用Pytorch从零开始实现CLIP

生成式建模知识回顾: [1] 生成式建模概述 [2] Transformer I&#xff0c;Transformer II [3] 变分自编码器 [4] 生成对抗网络&#xff0c;高级生成对抗网络 I&#xff0c;高级生成对抗网络 II [5] 自回归模型 [6] 归一化流模型 [7] 基于能量的模型 [8] 扩散模型 I, 扩散模型 II…

SS6811H38V/1.6A 两通道 H 桥驱动芯片

SS6811H 为舞台灯光和其它电机一体化应用 提供一种双通道集成电机驱动方案。SS6811H 有 两路 H 桥驱动&#xff0c;每个 H 桥可提供最大输出电流 1.6A (在 24V 和 Ta 25C 适当散热条件下)&#xff0c;可驱 动两个刷式直流电机&#xff0c;或者一个双极步进电机&#xff0c;或 …

python循环语句和函数

1.使用for循环打印9*9乘法表 for i in range(1, 10):for j in range(1, i1):print(i, "*", j, "", i*j, end"\t")print()结果&#xff1a; 2.使用while循环打印9*9乘法表 i 1 while i < 10:j 1while j < i1:print(i, "*", j…

【Openstack Train安装】六、Keystone安装

OpenStack是一个云计算平台的项目&#xff0c;其中Keystone是一个身份认证服务组件&#xff0c;它提供了认证、授权和目录的服务。其他OpenStack服务组件都需要使用Keystone来验证用户的身份和权限&#xff0c;并且彼此之间需要相互协作。当一个OpenStack服务组件接收到用户的请…