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

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();
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/205711.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【漏洞复现】熊海cms 存在sql注入 附poc

漏洞描述 熊海CMS 是由熊海开发的一款可广泛应用于个人博客,个人网站,企业网站的一套网站综合管理系统。 其采用前后端整合设计思路,php,Apache,mysql,前端使用Bootstrap和少许jquery前端框架开发; 网站样式设计简洁大方,整体功能点并不多,但功能正好够用;拥有一个…

【计网 面向连接的传输TCP】 中科大笔记 (十 二)

目录 0 引言1 TCP 的特性1.1 拓展&#xff1a;全双工、单工、半双工通信 2 TCP报文段结构3 TCP如何实现RDT4 TCP 流量控制4.1 题外话&#xff1a;算法感悟 5 TCP连接3次握手、断开连接4次握手5.1 连接5.2 断开连接 6 拥塞控制6.1 拥塞控制原理6.2 TCP拥塞控制 &#x1f64b;‍♂…

Docker容器网络模式

1.none网络 1&#xff09;使用默认网络模式创建一个BusyBox容器&#xff0c;用于对比none网络模式&#xff1b; 测试网络&#xff0c;可以正常连接外网。 2&#xff09;再创建一个none网络模式的BusyBox容器&#xff1b; 测试网络连接&#xff0c;无法连接外网。 总结&#x…

六:Day01_Spring Boot01

一、Spring Boot简介 1. 概念简介 Spring Boot是Spring公司的一个顶级项目&#xff0c;和Spring Framework是一个级别的。 Spring Boot实际上是利用Spring Framework 4 自动配置特性完成。编写项目时不需要编写xml文件。 2. 启动器介绍 Spring Boot的启动器实际上就是一个依赖…

TSINGSEE青犀AI视频智能分析系统的视频接入能力解析

视频智能分析技术是一种先进的人工智能技术&#xff0c;它能够对视频内容进行自动化的分析和理解。这种技术的主要特点包括实时性、自动化、准确性、可解释性等。 1&#xff09;实时性。视频智能分析技术能够在短时间内对大量的视频数据进行快速处理和分析&#xff0c;从而提供…

【网络BSP开发经验】网络流量应用识别技术

文章目录 网络流量应用识别技术背景应用识别基本原理应用识别主流技术方向特征识别技术单报文解析流特征解析 关联识别技术DNS关联识别 行为识别技术 应用识别框架介绍应用特征提取经验tcpdump 抓包方式默认启动监视指定网络接口的数据包监视指定主机的数据包 禁用特征提取加速…

Small Data Transmission (二)具体过程

这篇是SDT相关的具体过程,包括RRC层初始化SDT 的条件,MAC 层初始化SDT过程的判断,CG-SDT的具体过程,TA Validation for CG-SDT, CG-SDT TA 验证的路径损耗参考推导,SDT Uplink Time Alignment,RRC inactive中的CG based PUSCH传输和RA based PUSCH传输,依次看下。 初始…

简历上的工作经历怎么写

通过了简历筛选&#xff0c;后续的面试官会仔细阅读你的简历内容。他们在找什么呢&#xff1f;他们希望搞清楚你在某一段经历中具体干了什么&#xff0c;并且判断你的能力具体达到了什么水平。 简历在线制作下载&#xff1a;百度幻主简历 面试官喜欢具体的经历 越具体&#x…

计算机网络(二)

&#xff08;八&#xff09;客户端软件设计的细节 A、解析协议号 客户端可能会需要通过协议名指定协议&#xff0c;但是Socket接口是用协议号指定的&#xff0c;这时候我们就需要使用getprotobyname()函数实现协议名到协议号的转换&#xff0c;该函数会返回一个指向protoent的…

第三方实验室LIMS管理系统源码,asp.net LIMS源码

LIMS实验室信息管理系统源码 LIMS系统的功能根据实验室的规模和任务而有所不同&#xff0c;其系统主要功能包括:系统维护、基础数据编码管理&#xff0c;样品管理、数据管理、报告管理、报表打印、实验材料管理、设备管理等。它可以取代传统的手工管理模式而给检测实验室带来巨…

基于SSM框架的餐馆点餐系统的设计

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;Vue 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#xff1a;是 目录…

什么是Anaconda?作用是?使用python必须要安装嘛?

一、什么是Anaconda以及其作用&#xff1f; 通俗来讲&#xff0c;Anaconda算是一个环境容器&#xff0c;也可以叫环境管理器。 作用&#xff1a;可以在Anaconda容器中为python项目创建不同的环境。在各个不同环境中可以安装不同版本的包并且各个环境互不影响。可以在使用不同项…

唯品会年度特卖大会㊙内购清单㊙

唯品会年度特卖大会㊙内购清单㊙ 内部员工亲友专享&#xff0c;实实在在省钱&#xff0c;❌抢完不补! 今晚8点开抢&#xff0c;提前收藏>> https://t.vip.com/Im3KlTnDSJ8 2023年唯品会年度特卖大会热门会场推荐 1.唯品会年度特卖大会 限时加码!瓜分百万津贴!抢海量…

java论坛数据以及搜索接口实现

一. 内容简介 java论坛数据以及搜索接口实现 二. 软件环境 2.1 java 1.8 2.2 mysql Ver 8.0.13 for Win64 on x86_64 (MySQL Community Server - GPL) 2.3 IDEA ULTIMATE 2019.3 2.4d代码地址 三.主要流程 3.1 创建数据库,创建数据表 3.2 开始编写接口&#xff0c;并测…

字节大佬整理测试用例编写规范

目录 1.1目的 1.2使用范围 二 测试用例编写原则 2.1系统性 2.2连贯性 2.3全面性 2.4正确性 2.5符合正常业务惯例 2.6仿真性 2.7容错性&#xff08;健壮性&#xff09; 三 测试用例设计方法 3.1 等价类划分法&#xff1a; 3.2 边界值分析法&#xff1a; 3.3 因果图…

拼多多工作制;奥特曼回归;拼多多市值;雷军回应组装厂;| 每日科技小评

今日科技圈速览 马斯克称人工智能比核弹更危险奥特曼完整备忘录曝光 &#xff1a;未来发展有三大优先事项AI&#xff08;人工智能&#xff09;新锐巨头OpenAI的新董事会或许没有给投资者留下一席之地阿里巴巴市值又反超拼多多&#xff0c;长远来看拼多多和阿里巴巴哪个市值高&…

YOLO改进系列之ParNetAttention注意力机制

ParNet注意力是一种用于自然语言处理任务的注意力机制&#xff0c;它是由谷歌在2019年提出的。ParNet注意力旨在解决传统注意力机制在处理长序列时的效率问题。传统的注意力机制在计算注意力权重时&#xff0c;需要对所有输入序列的位置进行逐一计算&#xff0c;这导致了在长序…

JS中的类型转换

该节会全面介绍强制类型转换的优缺点 1、值类型转换 将值从一种类型转换为另一种类型通常称为类型转换&#xff0c;这是显式的情况&#xff1b;隐式的情况称为强制类型转换 JS中的强制类型转换总是返回标量基本类型值&#xff08;参见第 2 章&#xff09;&#xff0c;如字符…

5 存储器映射和寄存器

文章目录 5.3 芯片内核5.3.1 ICache5.3.2 DCache5.3.3 FlexRAM 5.4 存储器映射5.4.1 存储器功能划分5.4.1.1 存储器 Block0 内部区域功能划分5.4.1.2 储存器 Block1 内部区域功能划分5.4.1.3 储存器 Block2 内部区域功能划分 5.5 寄存器映射5.5.1 GPIO1的输出数据寄存器 5.3 芯…

如何使用内网穿透实现无公网ip环境访问VScode远程开发

文章目录 前言1、安装OpenSSH2、vscode配置ssh3. 局域网测试连接远程服务器4. 公网远程连接4.1 ubuntu安装cpolar内网穿透4.2 创建隧道映射4.3 测试公网远程连接 5. 配置固定TCP端口地址5.1 保留一个固定TCP端口地址5.2 配置固定TCP端口地址5.3 测试固定公网地址远程 前言 远程…