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

news2024/11/16 19:39:49

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.coloradmin.cn/o/1271957.html

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

相关文章

软件开发:基础源代码分享与入门指南

一、引言 软件开发是当今信息时代的一个热门领域&#xff0c;广泛应用于各个行业和领域&#xff0c;本文将向大家介绍软件开发的基础知识&#xff0c;并通过分享一些基础源代码&#xff0c;帮助大家更好地入门软件开发。 二、软件开发概述 软件开发是指通过编程语言和开发工…

容器有挂载目录的时候,容器反向生成为镜像,挂载的内容不会保留。只有实打实拷贝进容器的反向生成镜像才会保留。

无容器目录挂载 1、也就是说宿主机未与容器进行路径映射&#xff0c;故我们可以直接使用指令: docker commit 容器名称/容器ID 像名:标签号&#xff0c;把容器保存为镜像; (其中镜像名和标签号是我们随机取的&#xff0c;新镜像名以及我们的标签号!) 2、我们在不能判断容器与宿…

spring RedisTemplate RedisLockRegistry opsForXxx 基本使用总结以及介绍

一、基本介绍 RedisTemplate 为 spring 对 redis 操作的高度封装&#xff0c;基本已经满足所有使用场景。 若存在其他拓展使用我们可以自行封装工具类对基本操作进行组装。 RedisLockRegistry 对 redis 锁的一些封装 二、不同环境下依赖以及基本配置 2.1 spring-boot 下依赖…

【python】当当书籍数据抓取分析与可视化(代码+报告)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

Java多线程-第20章

Java多线程-第20章 1.创建线程 Java是一种支持多线程编程的编程语言。多线程是指在同一程序中同时执行多个独立任务的能力。在Java中&#xff0c;线程是一种轻量级的子进程&#xff0c;它是程序中的最小执行单元。Java的多线程编程可以通过两种方式实现&#xff1a;继承Threa…

【李肯C语言小册.目录】小册价值、内容目录汇总、加群方法 | 必看收藏.

小册订阅戳这里&#xff1a;【C语言小册 必读】为什么有这份专栏&#xff1f;解决什么问题&#xff1f;有哪些价值&#xff1f;是否值得订阅&#xff1f;-CSDN社区 订阅后&#xff0c;记得加微VX找我&#xff0c;发zhi付截图&#xff0c;备注【C语言小册】&#xff0c;拉你进本…

关于 SLO,我们需要了解什么?

什么是 SLO&#xff1f; SLO&#xff08;Service Level Objective&#xff09;是服务质量目标的短语缩写。它通常指的是维护系统的最高级别的目标&#xff0c;或服务等级协议&#xff08;SLA&#xff09;中的服务质量目标。它能够定义客户和用户在使用软件系统时所期望的服务质…

在直播间抢到好多实惠东东,全靠抖音支付

前不久我特别喜欢的一位主播的直播间做活动,很多我放在购物车里好久的心仪好物都有秒杀惊喜价。更让我开心的是,在拼手速抢这些秒杀好物的时候,我都成功了!这主要是因为我用了抖音支付,付款环节特别丝滑顺畅,让我在抖音的购物体验直接原地提升了几个level! 可能有朋友现在还是…

使用Docker安装Jenkins,解决插件安装失败,版本太低等问题

如果已经遇到插件安装部分失败&#xff0c;Jenkins版本太低&#xff0c;又要换什么清华镜像地址&#xff0c;不要犹豫&#xff0c;直接以下步骤卸载重装就好了 开始安装 yum 更新到最新 yum update到Jenkins官网查找最新的LST版本 最后的版本号一定要带&#xff0c;指定下载具…

9款高效绘图神器,提升你的工作效率

在日常工作或生活中&#xff0c;我们必须绘制各种图表、流程图、思维导图等图形&#xff0c;或者想用画笔描述自己的想法。然而&#xff0c;我们在许多绘图软件面前感到困惑。我们不知道哪个绘图软件好&#xff0c;也没有足够的时间一一尝试 在接下来的空间里&#xff0c;我们…

jmeter做接口自动化测试,你可能只是个新手!

jmeter 这个工具既可以做接口的功能测试&#xff0c;也可以做自动化测试&#xff0c;还可以做性能测试&#xff0c;其主要用途就是用于性能测试。但是&#xff0c;有些公司和个人&#xff0c;就想用 jmeter 来做接口自动化测试。 你有没有想过呢&#xff1f; 下面我就给大家讲…

深入了解小程序设计,六个关键要点全解析!

微信小程序开启了互联网软件的新使用模式。在各种微信小程序争相抢占流量的同时&#xff0c;如何设计微信小程序&#xff1f;让用户感到舒适是设计师在产品设计初期应该考虑的问题。那么如何做好微信小程序的设计呢&#xff1f;即时设计总结了以下设计指南&#xff0c;希望对准…

ProgrammingError: nan can not be used with MySQL

该错误怎么发生的&#xff1f; 我们先在本地创建测试表&#xff1a; CREATE TABLE users_test (id int NOT NULL AUTO_INCREMENT COMMENT 主键,trade_account varchar(50) DEFAULT NULL COMMENT 交易账号,username varchar(50) DEFAULT NULL,email varchar(100) DEFAULT NULL…

Cesium.CustomShader颜色值显示错误

官方示例&#xff1a; Cesium Sandcastle 测试过程&#xff1a; 1、修改示例&#xff0c;把customshader中的fragmentShaderText替换为如下代码 void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {//注意&#xff1a;下述颜色的b值是0.1&#x…

手把手教会你--办公软件--Word--持续更新

有什么问题&#xff0c;请尽情问博主&#xff0c;QQ群796141573 1.1 Word排版基础1 保存和命名Ⅰ自动保存 2 建立标准的编辑环境(1)显示编辑标记(2)打开标尺(3)打开导航窗格 3 高效的鼠标/键盘手势(1)连续选中内容--shift(2)跳选内容--ctrl(3)矩形选择内容--alt(4)回到文档开头…

全球79%的程序员都在考虑跳槽,你呢?

​在最近二十年中&#xff0c;全球行业都经历了一次数字化变革&#xff0c;各行各业对于技术开发的比重越来越高&#xff0c;而作为技术开发核心的开发人员们对于一个企业的未来发展也变得越来越重要。因此各企业对于技术人才的竞争变得火热&#xff0c;并且这个热度一年高过一…

SSM框架详解:结构创建与注解应用

文章目录 1. 引言2. SSM框架项目结构创建2.1 目录结构2.2 说明 3. 注解的应用3.1 Controller3.2 Service3.3 Repository3.4 Autowired3.5 RequestMapping3.6 Select、Insert等 4. 结语 &#x1f388;个人主页&#xff1a;程序员 小侯 &#x1f390;CSDN新晋作者 &#x1f389;欢…

传统家装“死气沉沉”?VR智慧家装提供VR可视化方案

传统家装市场虽然处于成熟期&#xff0c;但是对于装修小白的户主来说&#xff0c;难以解决的痛点依旧还有很多。很多家装公司所谓的设计师&#xff0c;不一定全都具备设计知识&#xff0c;也不懂得从客户的需求出发&#xff0c;多重因素导致家装行业“死气沉沉”。 为了打破装修…

振南技术干货集:各大平台串口调试软件大赏(4)

注解目录 &#xff08;串口的重要性不言而喻。为什么很多平台把串口称为 tty&#xff0c;比如 Linux、MacOS 等等&#xff0c;振南告诉你。&#xff09; 1、各平台上的串口调试软件 1.1Windows 1.1.1 STCISP &#xff08;感谢 STC 姚老板设计出 STCISP 这个软件。&#xf…

如何熟练使用vim工具?

&#x1f388;个人主页:&#x1f388; :✨✨✨初阶牛✨✨✨ &#x1f43b;推荐专栏1: &#x1f354;&#x1f35f;&#x1f32f;C语言初阶 &#x1f43b;推荐专栏2: &#x1f354;&#x1f35f;&#x1f32f;C语言进阶 &#x1f511;个人信条: &#x1f335;知行合一 &#x1f…