Wpf 使用 Prism 实战开发Day28

发布于:2024-05-30 ⋅ 阅读:(170) ⋅ 点赞:(0)

首页汇总方块点击导航功能

点击首页汇总方块的时候,跳转到对应的数据页面

step1: 在IndexViewModel 中,给TaskBar 里面Target 属性,赋上要跳转的页面

step2: 创建导航事件命令和方法实现

step3: 实现导航的逻辑。通过取到 IRegionManager 的实例中的Regions 找到首页的区域,并且通过RequestNavigate 导航到指定的目标页面。

step4: 导航到指定的目标页后,需要去接收导航传递过去的状态值2。例如当前是ToDoView,在 重写导航加载数据的方法中去接收到已完成的状态值 2,直接赋给SelectIndex,再重新加载数据。就可以根据状态查找出对应的数据了。

step5:最后,需要在IndexView.xaml 为汇总方块,添加点击事件触发器

  • MouseAction  触发类型

step 6:修改界面显示时间,动态绑定显示

step 7:对应的后台逻辑处理类IndexViewModel,创建出对应的属性并赋值

IndexViewModel 完整示例代码

public class IndexViewModel:NavigationViewModel
{
    private readonly IToDoService toDoService;
    private readonly IMemoService memoService;
    private readonly IRegionManager regionManager;
    public IndexViewModel(IDialogHostService dialogService,IContainerProvider provider):base(provider)
    {
        Title = $"你好,WPF{DateTime.Now.GetDateTimeFormats('D')[1]}";
        TaskBars=new ObservableCollection<TaskBar>();
        ExecuteCommand = new DelegateCommand<string>(Execute);
        EditTodoCommand = new DelegateCommand<ToDoDto>(AddTodo);
        EditMemoCommand = new DelegateCommand<MemoDto>(AddMemo);
        ToDoCompltedCommand = new DelegateCommand<ToDoDto>(Complted);
        NavigateCommand = new DelegateCommand<TaskBar>(Nvaigate);
        CreateTaskBars();
        this.toDoService = provider.Resolve<IToDoService>();//取到待办事项接口服务实例
        this.memoService = provider.Resolve<IMemoService>();
        this.regionManager=provider.Resolve<IRegionManager>();
        this.dialogService = dialogService;
    }

    public DelegateCommand<TaskBar> NavigateCommand { get; private set; }
    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 readonly IDialogHostService dialogService;
    private SummaryDto summaryDto;
    /// <summary>
    /// 首页统计
    /// </summary>
    public SummaryDto SummaryDto
    {
        get { return summaryDto; }
        set { summaryDto = value; RaisePropertyChanged(); }
    }

    private string title;
    /// <summary>
    /// 标题
    /// </summary>
    public string Title
    {
        get { return title; }
        set { title = value;RaisePropertyChanged(); }
    }

    void CreateTaskBars()
    {
        TaskBars.Add(new TaskBar() { Icon="ClockFast",Title="汇总",Color="#FF0CA0FF",Target= "ToDoView" });
        TaskBars.Add(new TaskBar() { Icon = "ClockCheckOutline", Title = "已完成", Color = "#FF1ECA3A", Target = "ToDoView" });
        TaskBars.Add(new TaskBar() { Icon = "ChartLineVariant", Title = "完成比例", Color = "#FF02C6DC", Target = "" });
        TaskBars.Add(new TaskBar() { Icon = "PlaylistStar", Title = "备忘录", Color = "#FFFFA000", Target = "MemoView" });
    }
    void RefreshBars()
    {
        TaskBars[0].Content = summaryDto.Sum.ToString();
        TaskBars[1].Content = summaryDto.CompletedCount.ToString();
        TaskBars[2].Content = summaryDto.CompletedRatio;
        TaskBars[3].Content = summaryDto.MemoeCount.ToString();
    }
    
    public override  void OnNavigatedTo(NavigationContext navigationContext)
    {
        GetSummaryAsync();
        base.OnNavigatedTo(navigationContext);
    }
    /// <summary>
    /// 获取汇总数据
    /// </summary>
    async void GetSummaryAsync()
    {
        var summaryResult = await toDoService.SummaryAsync();
        if (summaryResult.Status)
        {
            SummaryDto = summaryResult.Result;
            RefreshBars();
        }
    }
    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 = SummaryDto.MemoList.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)
                {
                    SummaryDto.MemoList.Add(addResult.Result);//添加到界面的集合中
                }
            }
            GetSummaryAsync();
            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= SummaryDto.TodoList.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)
                {
                    SummaryDto.TodoList.Add(addResult.Result);//添加到界面的集合中
                }
            }
            GetSummaryAsync();
            UpdateLoading(false);
        }
    }

    private async void Complted(ToDoDto dto)
    {
       var updateResult=await toDoService.UpdateAsync(dto);//根据传过来的对象进行更新
        if(updateResult.Status)
        {
           var todo= SummaryDto.TodoList.FirstOrDefault(t=>t.Id.Equals(dto.Id));//在界面数据列表中找到这条数据
           if(todo != null)
            {
                SummaryDto.TodoList.Remove(todo);
                GetSummaryAsync();
            }
        }
    }
    private void Nvaigate(TaskBar bar)
    {
        if (string.IsNullOrWhiteSpace(bar.Target)) return;

        //创建导航传递的参数
        NavigationParameters pairs = new NavigationParameters();
        if (bar.Title == "已完成")
        {
            pairs.Add("Value",2);//传递完成的参数过去
        }
        regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(bar.Target,pairs);
    }
}

IndexView.xaml  完整示例代码

<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="{Binding Title}"/>

        <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.InputBindings>
                            <MouseBinding MouseAction="RightClick"
                                          Command="{Binding DataContext.NavigateCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ItemsControl}}"
                                          CommandParameter="{Binding}"/>
                        </Border.InputBindings>
                        <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 SummaryDto.TodoList}" 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 SummaryDto.MemoList}"  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>

网站公告

今日签到

点亮在社区的每一天
去签到