Wpf 使用 Prism 实战开发Day26

首页待办事项编辑和完成以及备忘录编辑功能

当用户双击待办事项或备忘录的时候,希望能进行编辑待办事项及备忘录的功能

一.在IndexView.xaml 视图,为待办和备忘录添加双击编辑功能

1.首先引入一个 behaviors 命名空间,用于进行处理鼠标双击事件的交互

XML 复制代码
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"

2.在ListBox (数据展示区) 增加一个鼠标双击的动作,以及进行相关命令绑定

XML 复制代码
<!--鼠标双击-->
<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseDoudleClick">
        <i:InvokeCommandAction  Command="{Binding AddTodoCommand}"
                                CommandParameter="{Binding ElementName=todoList,Path=SelectedItem}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
  • ElementName属性用于在XAML中引用其他命名元素的名称,以便进行数据绑定或其他操作
  • Path属性允许指定从数据上下文对象中提取的值的路径

3.IndexView.xaml 完整的示例代码

XML 复制代码
<UserControl x:Class="MyToDo.Views.IndexView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyToDo.Views"
             mc:Ignorable="d" 
             xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Margin="15,10" FontSize="22" Text="你好,WPF! 今天是2023-11-12 星期天"/>

        <ItemsControl Grid.Row="1" ItemsSource="{Binding TaskBars}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Columns="4"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <!--模板内容设计-->
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border Background="{Binding Color}" CornerRadius="5" Margin="10">
                        <Border.Style>
                            <Style TargetType="Border">
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Effect">
                                            <Setter.Value>
                                                <DropShadowEffect Color="#DDDDDD" ShadowDepth="1" BlurRadius="10" />
                                            </Setter.Value>
                                        </Setter>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Border.Style>
                        <Grid>
                            <StackPanel Margin="20,10">
                                <!--图标-->
                                <materialDesign:PackIcon Kind="{Binding Icon}" Width="30" Height="30" />
                                <!--标题文本-->
                                <TextBlock Text="{Binding Title}" Margin="0,15" FontSize="15"/>
                                <!--内容-->
                                <TextBlock Text="{Binding Content}" FontWeight="Bold" FontSize="40"/>
                            </StackPanel>
                            <!--白色背景底色控件-->
                            <Canvas ClipToBounds="True">
                                <Border Canvas.Top="10" CornerRadius="100" Canvas.Right="-50" Width="120" Height="120" Background="#ffffff" Opacity="0.1"/>
                                <Border Canvas.Top="80" CornerRadius="100" Canvas.Right="-30" Width="120" Height="120" Background="#ffffff" Opacity="0.1"/>
                            </Canvas>
                        </Grid>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

        <Grid Grid.Row="2" Margin="0,10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
             
            <!--外边框-->
            <Border Margin="10,0" Background="#BEBEBE" CornerRadius="5" Opacity="0.1"/>
            <Border Grid.Column="1" Margin="10,0" Background="#BEBEBE" CornerRadius="5" Opacity="0.1"/>
            
            <!--主体内容左-->
            <DockPanel Margin="10,0">
                <DockPanel Margin="10,5" LastChildFill="False" DockPanel.Dock="Top">
                    <TextBlock Text="待办事项" FontSize="20" FontWeight="Bold"/>
                    <Button Width="30" Height="30" VerticalAlignment="Top" DockPanel.Dock="Right" Style="{StaticResource MaterialDesignFloatingActionAccentButton}" 
                            Command="{Binding ExecuteCommand}" CommandParameter="新增待办事项">
                        <materialDesign:PackIcon Kind="Add" />
                    </Button>
                </DockPanel>
                <!--数据列表区域-->
                <ListBox x:Name="todoList" ItemsSource="{Binding ToDoDtos}" ScrollViewer.VerticalScrollBarVisibility="Hidden" HorizontalContentAlignment="Stretch" >
                    <!--鼠标双击-->
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseDoubleClick">
                            <i:InvokeCommandAction  Command="{Binding EditTodoCommand}"
                                                    CommandParameter="{Binding ElementName=todoList,Path=SelectedItem}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <DockPanel MaxHeight="80" LastChildFill="False">
                                <ToggleButton DockPanel.Dock="Right"/>
                                <StackPanel>
                                    <TextBlock Text="{Binding Title}" FontSize="16" FontWeight="Bold"/>
                                    <TextBlock Text="{Binding Content}" Margin="0,5" Opacity="0.5" />
                                </StackPanel>
                            </DockPanel>
                           
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </DockPanel>

            <!--主体内容右-->
            <DockPanel  Grid.Column="1" Margin="10,0">
                <DockPanel Margin="10,5" LastChildFill="False" DockPanel.Dock="Top">
                    <TextBlock Text="备忘录" FontSize="20" FontWeight="Bold"/>
                    <Button Width="30" Height="30" VerticalAlignment="Top" DockPanel.Dock="Right" Style="{StaticResource MaterialDesignFloatingActionAccentButton}" 
                            Command="{Binding ExecuteCommand}" CommandParameter="新增备忘录">
                        <materialDesign:PackIcon Kind="Add" />
                    </Button>
                </DockPanel>
                <!--数据列表区域-->
                <ListBox x:Name="memoList"  ItemsSource="{Binding MemoDtos}"  ScrollViewer.VerticalScrollBarVisibility="Hidden" >
                    <!--鼠标双击-->
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseDoubleClick">
                            <i:InvokeCommandAction  Command="{Binding EditMemoCommand}"
                                CommandParameter="{Binding ElementName=memoList,Path=SelectedItem}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel MaxHeight="80">
                                <TextBlock Text="{Binding Title}" FontSize="16" FontWeight="Bold"/>
                                <TextBlock Text="{Binding Content}" Margin="0,5" Opacity="0.5" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </DockPanel>
        </Grid>
    </Grid>
</UserControl>

二.修改IndexViewModel 视图逻辑处理类,实现视图中命令绑定处理逻辑

1.为待办事项和备忘录添加双击命令绑定的处理逻辑,然后根据传过来的Model 实体,是不是空来判断走的增加还是编辑

待办事项和备忘录编辑功能完整示例代码

cs 复制代码
public class IndexViewModel:NavigationViewModel
{
    private readonly IToDoService toDoService;
    private readonly IMemoService memoService;
    public IndexViewModel(IDialogHostService dialogService,IContainerProvider provider):base(provider)
    {
        TaskBars=new ObservableCollection<TaskBar>();
        ToDoDtos = new ObservableCollection<ToDoDto>();
        MemoDtos = new ObservableCollection<MemoDto>();
        ExecuteCommand = new DelegateCommand<string>(Execute);
        EditTodoCommand = new DelegateCommand<ToDoDto>(AddTodo);
        EditMemoCommand = new DelegateCommand<MemoDto>(AddMemo);
        CreateTaskBars();
        this.toDoService = provider.Resolve<IToDoService>();//取到待办事项接口服务实例
        this.memoService = provider.Resolve<IMemoService>();
        this.dialogService = dialogService;
    }

    public DelegateCommand<ToDoDto> EditTodoCommand { get; private set; } //待办事项双击绑定命令
    public DelegateCommand<MemoDto> EditMemoCommand { get; private set; } //备忘录双击绑定命令
    public DelegateCommand<string> ExecuteCommand { get; private set; }
        
    private ObservableCollection<TaskBar> taskBars;

    public ObservableCollection<TaskBar> TaskBars
    {
        get { return taskBars; }
        set { taskBars = value; RaisePropertyChanged(); }
    }
    private ObservableCollection<ToDoDto> toDoDtos;

    public ObservableCollection<ToDoDto> ToDoDtos
    {
        get { return toDoDtos; }
        set { toDoDtos = value; RaisePropertyChanged(); }
    }
    private ObservableCollection<MemoDto> memoDtos;
    private readonly IDialogHostService dialogService;

    public ObservableCollection<MemoDto> MemoDtos
    {
        get { return memoDtos; }
        set { memoDtos = value; RaisePropertyChanged(); }
    }
    void CreateTaskBars()
    {
        TaskBars.Add(new TaskBar() { Icon="ClockFast",Title="汇总",Content="9",Color="#FF0CA0FF",Target=""});
        TaskBars.Add(new TaskBar() { Icon = "ClockCheckOutline", Title = "已完成", Content = "9", Color = "#FF1ECA3A", Target = "" });
        TaskBars.Add(new TaskBar() { Icon = "ChartLineVariant", Title = "完成比例", Content = "9%", Color = "#FF02C6DC", Target = "" });
        TaskBars.Add(new TaskBar() { Icon = "PlaylistStar", Title = "备忘录", Content = "18", Color = "#FFFFA000", Target = "" });
    }
    async void GetDataAsync()
    {
        //加载备忘录数据
        var memoResult = await memoService.GetAllAsync(new Shared.Parameters.QueryParameter()
        {
            PageIndex = 0,
            PageSize = 100
        });
        if (memoResult.Status)
        {
            MemoDtos.Clear();
            foreach (var item in memoResult.Result.Items)
            {
                MemoDtos.Add(item);
            }
        }
        //加载待办事项数据
        var todoResult = await toDoService.GetAllAsync(new Shared.Parameters.QueryParameter()
        {
            PageIndex = 0,
            PageSize = 100
        });
        if (todoResult.Status)
        {
            ToDoDtos.Clear();
            foreach (var item in todoResult.Result.Items)
            {
                ToDoDtos.Add(item);
            }
        }
    }
    public override void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);
        GetDataAsync();
    }
    private void Execute(string obj)
    {
       switch(obj)
        {
            case "新增备忘录":
                AddMemo();
                break;
            case "新增待办事项":
                AddTodo();
                break;
        }
    }
    async void AddMemo(MemoDto? model =null)
    {
        DialogParameters param = new DialogParameters();
        if (model != null)//如果是编辑
        {
            param.Add("Value",model);//把要编辑的数据传过去
        }
        var dialogMemoResult = await dialogService.ShowDialog("AddMemoView", param, "RootDialog");
        if (dialogMemoResult.Result == ButtonResult.OK)
        {
            UpdateLoading(true);
            var memo = dialogMemoResult.Parameters.GetValue<MemoDto>("Value");//获取到弹窗传过来的值
            if (memo.Id > 0)//编辑
            {
                var updateResult = await memoService.UpdateAsync(memo);
                if (updateResult.Status)//更新成功
                {
                    var memoModel = MemoDtos.FirstOrDefault(it => it.Id.Equals(memo.Id));//在界面的数据集合中,找到要更新的那条数据
                    if (memoModel != null)
                    {
                        memoModel.Title = memo.Title;
                        memoModel.Content = memo.Content;
                    }
                }
            }
            else
            {
                //新增
                var addResult = await memoService.AddAsync(memo);
                if (addResult.Status)
                {
                    MemoDtos.Add(addResult.Result);//添加到界面的集合中
                }
            }
            UpdateLoading(false);
        }
    }
    async void AddTodo(ToDoDto? model = null)
    {
        DialogParameters param = new DialogParameters();
        if (model != null)//如果是编辑
        {
            param.Add("Value", model);//把要编辑的数据传过去
        }
        var dialogToDoResult = await dialogService.ShowDialog("AddToDoView", param, "RootDialog");
        if (dialogToDoResult.Result == ButtonResult.OK)
        {
            UpdateLoading(true);
            var todo = dialogToDoResult.Parameters.GetValue<ToDoDto>("Value");//获取到弹窗传过来的值
            if (todo.Id > 0)//编辑
            {
               var updateResult=await toDoService.UpdateAsync(todo);
                if(updateResult.Status)//更新成功
                {
                   var todoModel= ToDoDtos.FirstOrDefault(it => it.Id.Equals(todo.Id));//在界面的数据集合中,找到要更新的那条数据
                    if (todoModel != null)
                    {
                        todoModel.Title = todo.Title;
                        todoModel.Content= todo.Content;
                    }
                }
            }
            else
            {
                //新增
                var addResult = await toDoService.AddAsync(todo);
                if (addResult.Status)
                {
                    ToDoDtos.Add(addResult.Result);//添加到界面的集合中
                }
            }
            UpdateLoading(false);
        }
    }
}

三.待办事项,实现完成状态更新功能

当待办事项右侧按钮点击完成的时候,把待办事项从列表中移除掉。

1.修改在IndexView.xaml 视图

1.1 为ToggleButton 添加绑定命令,通过查找绑定的方式进行命令绑定

首先,通过设置查找类型为 ItemsControl,并通过ItemsControl 来获取到对应的DataContext(数据上下文)来找到绑定的命令ToDoCompltedCommand。并且还需要为ToggleButton 进行绑定数据源

1.2 由于后台对应的Status 为Int类型,1或0。但前端ToggleButton 的开关按钮是需要传 一个Bool 类型值,True或False.所以需要给ToggleButton 前端页面和后台处理添加数据类型转换器
1.2.1 创建转换器 IntToBoolConveter
cs 复制代码
namespace MyToDo.Common.Converters
{
    /// <summary>
    /// 转换器
    /// </summary>
    public class IntToBoolConveter : IValueConverter
    {
        //前端把后端int 类型转换成前端要用的bool值
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value!=null && int.TryParse(value.ToString(), out int result))
            {
                if(result ==0) return false;
            }
          
            return true;
        }
        //前端把boo值,转换成后端需要的int值给后端
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && bool.TryParse(value.ToString(), out bool result))
            {
                if (result) return 1;
            }
            return 0;
        }
    }
}
1.2.2 转换器创建完成后,需要为前端页面,引入转换器,并在ToggleButton 控件中使用。
  • 首先引入转换器命名空间
  • 创建控件资源文件,并定义唯一的key
  • 在toggleButton中通过key,来使用到资源转换器
1.3 还需要为 ToggleButton 绑定参数

绑定的参数为当前整个对象。直接写成 CommandParameter="{Binding}" 即可。表示传递的参数是整个对象。

2.完整的IndexView.xaml 视图示例代码

XML 复制代码
<UserControl x:Class="MyToDo.Views.IndexView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyToDo.Views"
             mc:Ignorable="d" 
             xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
             xmlns:cv="clr-namespace:MyToDo.Common.Converters"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.Resources>
        <cv:IntToBoolConveter x:Key="intToBool"/>
    </UserControl.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Margin="15,10" FontSize="22" Text="你好,WPF! 今天是2023-11-12 星期天"/>

        <ItemsControl Grid.Row="1" ItemsSource="{Binding TaskBars}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Columns="4"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <!--模板内容设计-->
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border Background="{Binding Color}" CornerRadius="5" Margin="10">
                        <Border.Style>
                            <Style TargetType="Border">
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Effect">
                                            <Setter.Value>
                                                <DropShadowEffect Color="#DDDDDD" ShadowDepth="1" BlurRadius="10" />
                                            </Setter.Value>
                                        </Setter>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Border.Style>
                        <Grid>
                            <StackPanel Margin="20,10">
                                <!--图标-->
                                <materialDesign:PackIcon Kind="{Binding Icon}" Width="30" Height="30" />
                                <!--标题文本-->
                                <TextBlock Text="{Binding Title}" Margin="0,15" FontSize="15"/>
                                <!--内容-->
                                <TextBlock Text="{Binding Content}" FontWeight="Bold" FontSize="40"/>
                            </StackPanel>
                            <!--白色背景底色控件-->
                            <Canvas ClipToBounds="True">
                                <Border Canvas.Top="10" CornerRadius="100" Canvas.Right="-50" Width="120" Height="120" Background="#ffffff" Opacity="0.1"/>
                                <Border Canvas.Top="80" CornerRadius="100" Canvas.Right="-30" Width="120" Height="120" Background="#ffffff" Opacity="0.1"/>
                            </Canvas>
                        </Grid>
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

        <Grid Grid.Row="2" Margin="0,10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
             
            <!--外边框-->
            <Border Margin="10,0" Background="#BEBEBE" CornerRadius="5" Opacity="0.1"/>
            <Border Grid.Column="1" Margin="10,0" Background="#BEBEBE" CornerRadius="5" Opacity="0.1"/>
            
            <!--主体内容左-->
            <DockPanel Margin="10,0">
                <DockPanel Margin="10,5" LastChildFill="False" DockPanel.Dock="Top">
                    <TextBlock Text="待办事项" FontSize="20" FontWeight="Bold"/>
                    <Button Width="30" Height="30" VerticalAlignment="Top" DockPanel.Dock="Right" Style="{StaticResource MaterialDesignFloatingActionAccentButton}" 
                            Command="{Binding ExecuteCommand}" CommandParameter="新增待办事项">
                        <materialDesign:PackIcon Kind="Add" />
                    </Button>
                </DockPanel>
                <!--数据列表区域-->
                <ListBox x:Name="todoList" ItemsSource="{Binding ToDoDtos}" ScrollViewer.VerticalScrollBarVisibility="Hidden" HorizontalContentAlignment="Stretch" >
                    <!--鼠标双击-->
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseDoubleClick">
                            <i:InvokeCommandAction  Command="{Binding EditTodoCommand}"
                                                    CommandParameter="{Binding ElementName=todoList,Path=SelectedItem}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <DockPanel MaxHeight="80" LastChildFill="False">
                                <ToggleButton DockPanel.Dock="Right" Command="{Binding DataContext.ToDoCompltedCommand,
                                     RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ItemsControl}}" IsChecked="{Binding Status,Converter={StaticResource intToBool}}"
                                              CommandParameter="{Binding}"/>
                                <StackPanel>
                                    <TextBlock Text="{Binding Title}" FontSize="16" FontWeight="Bold"/>
                                    <TextBlock Text="{Binding Content}" Margin="0,5" Opacity="0.5" />
                                </StackPanel>
                            </DockPanel>
                           
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </DockPanel>

            <!--主体内容右-->
            <DockPanel  Grid.Column="1" Margin="10,0">
                <DockPanel Margin="10,5" LastChildFill="False" DockPanel.Dock="Top">
                    <TextBlock Text="备忘录" FontSize="20" FontWeight="Bold"/>
                    <Button Width="30" Height="30" VerticalAlignment="Top" DockPanel.Dock="Right" Style="{StaticResource MaterialDesignFloatingActionAccentButton}" 
                            Command="{Binding ExecuteCommand}" CommandParameter="新增备忘录">
                        <materialDesign:PackIcon Kind="Add" />
                    </Button>
                </DockPanel>
                <!--数据列表区域-->
                <ListBox x:Name="memoList"  ItemsSource="{Binding MemoDtos}"  ScrollViewer.VerticalScrollBarVisibility="Hidden" >
                    <!--鼠标双击-->
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseDoubleClick">
                            <i:InvokeCommandAction  Command="{Binding EditMemoCommand}"
                                CommandParameter="{Binding ElementName=memoList,Path=SelectedItem}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel MaxHeight="80">
                                <TextBlock Text="{Binding Title}" FontSize="16" FontWeight="Bold"/>
                                <TextBlock Text="{Binding Content}" Margin="0,5" Opacity="0.5" />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </DockPanel>
        </Grid>
    </Grid>
</UserControl>

3.最后,在视图逻辑处理类中,实现绑定的ToDoCompltedCommand 命令逻辑

1.创建命令并实例化
2.处理逻辑

4.IndexViewModel.cs 逻辑处理类完整示例代码

cs 复制代码
public class IndexViewModel:NavigationViewModel
{
    private readonly IToDoService toDoService;
    private readonly IMemoService memoService;
    public IndexViewModel(IDialogHostService dialogService,IContainerProvider provider):base(provider)
    {
        TaskBars=new ObservableCollection<TaskBar>();
        ToDoDtos = new ObservableCollection<ToDoDto>();
        MemoDtos = new ObservableCollection<MemoDto>();
        ExecuteCommand = new DelegateCommand<string>(Execute);
        EditTodoCommand = new DelegateCommand<ToDoDto>(AddTodo);
        EditMemoCommand = new DelegateCommand<MemoDto>(AddMemo);
        ToDoCompltedCommand = new DelegateCommand<ToDoDto>(Complted);
        CreateTaskBars();
        this.toDoService = provider.Resolve<IToDoService>();//取到待办事项接口服务实例
        this.memoService = provider.Resolve<IMemoService>();
        this.dialogService = dialogService;
    }
    public DelegateCommand<ToDoDto> ToDoCompltedCommand {  get; private set; }//完成按钮绑定命令
    public DelegateCommand<ToDoDto> EditTodoCommand { get; private set; } //待办事项双击绑定命令
    public DelegateCommand<MemoDto> EditMemoCommand { get; private set; } //备忘录双击绑定命令
    
    public DelegateCommand<string> ExecuteCommand { get; private set; }
        
    private ObservableCollection<TaskBar> taskBars;

    public ObservableCollection<TaskBar> TaskBars
    {
        get { return taskBars; }
        set { taskBars = value; RaisePropertyChanged(); }
    }
    private ObservableCollection<ToDoDto> toDoDtos;

    public ObservableCollection<ToDoDto> ToDoDtos
    {
        get { return toDoDtos; }
        set { toDoDtos = value; RaisePropertyChanged(); }
    }
    private ObservableCollection<MemoDto> memoDtos;
    private readonly IDialogHostService dialogService;

    public ObservableCollection<MemoDto> MemoDtos
    {
        get { return memoDtos; }
        set { memoDtos = value; RaisePropertyChanged(); }
    }
    void CreateTaskBars()
    {
        TaskBars.Add(new TaskBar() { Icon="ClockFast",Title="汇总",Content="9",Color="#FF0CA0FF",Target=""});
        TaskBars.Add(new TaskBar() { Icon = "ClockCheckOutline", Title = "已完成", Content = "9", Color = "#FF1ECA3A", Target = "" });
        TaskBars.Add(new TaskBar() { Icon = "ChartLineVariant", Title = "完成比例", Content = "9%", Color = "#FF02C6DC", Target = "" });
        TaskBars.Add(new TaskBar() { Icon = "PlaylistStar", Title = "备忘录", Content = "18", Color = "#FFFFA000", Target = "" });
    }
    async void GetDataAsync()
    {
        //加载备忘录数据
        var memoResult = await memoService.GetAllAsync(new Shared.Parameters.QueryParameter()
        {
            PageIndex = 0,
            PageSize = 100
        });
        if (memoResult.Status)
        {
            MemoDtos.Clear();
            foreach (var item in memoResult.Result.Items)
            {
                MemoDtos.Add(item);
            }
        }
        //加载待办事项数据
        var todoResult = await toDoService.GetAllAsync(new Shared.Parameters.QueryParameter()
        {
            PageIndex = 0,
            PageSize = 100
        });
        if (todoResult.Status)
        {
            ToDoDtos.Clear();
            foreach (var item in todoResult.Result.Items)
            {
                ToDoDtos.Add(item);
            }
        }
    }
    public override void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);
        GetDataAsync();
    }
    private void Execute(string obj)
    {
       switch(obj)
        {
            case "新增备忘录":
                AddMemo();
                break;
            case "新增待办事项":
                AddTodo();
                break;
        }
    }
    async void AddMemo(MemoDto? model =null)
    {
        DialogParameters param = new DialogParameters();
        if (model != null)//如果是编辑
        {
            param.Add("Value",model);//把要编辑的数据传过去
        }
        var dialogMemoResult = await dialogService.ShowDialog("AddMemoView", param, "RootDialog");
        if (dialogMemoResult.Result == ButtonResult.OK)
        {
            UpdateLoading(true);
            var memo = dialogMemoResult.Parameters.GetValue<MemoDto>("Value");//获取到弹窗传过来的值
            if (memo.Id > 0)//编辑
            {
                var updateResult = await memoService.UpdateAsync(memo);
                if (updateResult.Status)//更新成功
                {
                    var memoModel = MemoDtos.FirstOrDefault(it => it.Id.Equals(memo.Id));//在界面的数据集合中,找到要更新的那条数据
                    if (memoModel != null)
                    {
                        memoModel.Title = memo.Title;
                        memoModel.Content = memo.Content;
                    }
                }
            }
            else
            {
                //新增
                var addResult = await memoService.AddAsync(memo);
                if (addResult.Status)
                {
                    MemoDtos.Add(addResult.Result);//添加到界面的集合中
                }
            }
            UpdateLoading(false);
        }
    }
    async void AddTodo(ToDoDto? model = null)
    {
        DialogParameters param = new DialogParameters();
        if (model != null)//如果是编辑
        {
            param.Add("Value", model);//把要编辑的数据传过去
        }
        var dialogToDoResult = await dialogService.ShowDialog("AddToDoView", param, "RootDialog");
        if (dialogToDoResult.Result == ButtonResult.OK)
        {
            UpdateLoading(true);
            var todo = dialogToDoResult.Parameters.GetValue<ToDoDto>("Value");//获取到弹窗传过来的值
            if (todo.Id > 0)//编辑
            {
               var updateResult=await toDoService.UpdateAsync(todo);
                if(updateResult.Status)//更新成功
                {
                   var todoModel= ToDoDtos.FirstOrDefault(it => it.Id.Equals(todo.Id));//在界面的数据集合中,找到要更新的那条数据
                    if (todoModel != null)
                    {
                        todoModel.Title = todo.Title;
                        todoModel.Content= todo.Content;
                    }
                }
            }
            else
            {
                //新增
                var addResult = await toDoService.AddAsync(todo);
                if (addResult.Status)
                {
                    ToDoDtos.Add(addResult.Result);//添加到界面的集合中
                }
            }
            UpdateLoading(false);
        }
    }

    private async void Complted(ToDoDto dto)
    {
       var updateResult=await toDoService.UpdateAsync(dto);//根据传过来的对象进行更新
        if(updateResult.Status)
        {
           var todo= ToDoDtos.FirstOrDefault(t=>t.Id.Equals(dto.Id));//在界面数据列表中找到这条数据
           if(todo != null)
            {
                ToDoDtos.Remove(todo);
            }
        }
    }
}
相关推荐
Java Fans2 小时前
C# 中串口读取问题及解决方案
开发语言·c#
盛派网络小助手3 小时前
微信 SDK 更新 Sample,NCF 文档和模板更新,更多更新日志,欢迎解锁
开发语言·人工智能·后端·架构·c#
码农君莫笑3 小时前
信管通低代码信息管理系统应用平台
linux·数据库·windows·低代码·c#·.net·visual studio
鲤籽鲲4 小时前
C# Random 随机数 全面解析
android·java·c#
fkdw6 小时前
C# Newtonsoft.Json 反序列化派生类数据丢失问题
c#·json
浅尝辄止;9 小时前
C# 异步编程
c#
ou.cs13 小时前
c# 实现一个简单的异常日志记录(异常迭代+分片+定时清理)+AOP Rougamo全局注入
c#
~央千澈~14 小时前
优雅草央千澈-关于蓝湖如何快速的标注交互原型是如何使用的-如何使用蓝湖设计交互原型和整个软件项目的流程逻辑-实践项目详细说明
ui·交互·蓝湖