WPF中实现动态导航

主页面

<mah:MetroWindow
    x:Class="Kx.View.MyMainView"
    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:hc="https://handyorg.github.io/handycontrol"
    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    xmlns:local="clr-namespace:Kx.View"
    xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:mv="clr-namespace:Kx.ViewModel"
    Title="KxMes系统"
    Width="1024"
    Height="768"
    d:DataContext="{d:DesignInstance mv:MyMainViewModel}"
    Background="{StaticResource AppBackground}"
    WindowStartupLocation="CenterScreen"
    WindowState="Maximized"
    mc:Ignorable="d">
    <mah:MetroWindow.Resources>
        <Storyboard x:Key="OnChecked1">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="leftBorder" Storyboard.TargetProperty="(FrameworkElement.Width)">
                <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="45" />
            DoubleAnimationUsingKeyFrames>
        Storyboard>
        <Storyboard x:Key="OnUnchecked1">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="leftBorder" Storyboard.TargetProperty="(FrameworkElement.Width)">
                <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="200" />
            DoubleAnimationUsingKeyFrames>
        Storyboard>
    mah:MetroWindow.Resources>
    <mah:MetroWindow.Triggers>
        <EventTrigger RoutedEvent="ToggleButton.Checked" SourceName="toggleButton">
            <BeginStoryboard Storyboard="{StaticResource OnChecked1}" />
        EventTrigger>
        <EventTrigger RoutedEvent="ToggleButton.Unchecked" SourceName="toggleButton">
            <BeginStoryboard Storyboard="{StaticResource OnUnchecked1}" />
        EventTrigger>
    mah:MetroWindow.Triggers>
    <Grid>
        <Grid
            x:Name="markLayer"
            Panel.ZIndex="999"
            Background="Black"
            Opacity="0.8"
            Visibility="Hidden" />
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto" />
                <ColumnDefinition />
            Grid.ColumnDefinitions>
            
            <Border
                x:Name="leftBorder"
                Width="200"
                Background="#2B2C31"
                BorderThickness="0,0,1,0">
                <Border.Effect>
                    <DropShadowEffect
                        BlurRadius="10"
                        Opacity="0.5"
                        ShadowDepth="0"
                        Color="Black" />
                Border.Effect>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="auto" />
                        <RowDefinition />
                    Grid.RowDefinitions>
                    <StackPanel
                        Grid.Row="0"
                        Margin="0,15,0,15"
                        Orientation="Horizontal">
                        <StackPanel.Effect>
                            <DropShadowEffect
                                BlurRadius="10"
                                Opacity="1"
                                ShadowDepth="0"
                                Color="Black" />
                        StackPanel.Effect>
                        <TextBlock
                            Margin="5,5,5,5"
                            FontSize="20"
                            Foreground="#297790"
                            Style="{DynamicResource CustomTextBlockStyle}"
                            Text="" />
                        <TextBlock
                            VerticalAlignment="Center"
                            FontFamily="Fonts/#FontAwesome"
                            FontSize="22"
                            Foreground="White"
                            Text=" KxMES系统" />
                    StackPanel>
                    <StackPanel Grid.Row="1">
                        <RadioButton
                            Width="200"
                            Height="50"
                            Content="首页"
                            FontSize="18"
                            Foreground="White"
                            Style="{DynamicResource RadioButtonMenuStyle}"
                            Tag="">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <i:InvokeCommandAction Command="{Binding SelectView}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=RadioButton}}" />
                                i:EventTrigger>
                            i:Interaction.Triggers>
                        RadioButton>
                        <RadioButton
                            Width="200"
                            Height="50"
                            Content="页面1"
                            FontSize="18"
                            Foreground="White"
                            Style="{DynamicResource RadioButtonMenuStyle}"
                            Tag="">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <i:InvokeCommandAction Command="{Binding SelectView}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=RadioButton}}" />
                                i:EventTrigger>
                            i:Interaction.Triggers>
                        RadioButton>
                        <RadioButton
                            Width="200"
                            Height="50"
                            Content="物资管理"
                            FontSize="18"
                            Foreground="White"
                            Style="{DynamicResource RadioButtonMenuStyle}"
                            Tag="">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <i:InvokeCommandAction Command="{Binding SelectView}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=RadioButton}}" />
                                i:EventTrigger>
                            i:Interaction.Triggers>
                        RadioButton>
                        <RadioButton
                            Width="200"
                            Height="50"
                            Content="工艺管理"
                            FontSize="18"
                            Foreground="White"
                            Style="{DynamicResource RadioButtonMenuStyle}"
                            Tag="">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <i:InvokeCommandAction Command="{Binding SelectView}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=RadioButton}}" />
                                i:EventTrigger>
                            i:Interaction.Triggers>
                        RadioButton>
                        <RadioButton
                            Width="200"
                            Height="50"
                            Content="设备类型"
                            FontSize="18"
                            Foreground="White"
                            Style="{DynamicResource RadioButtonMenuStyle}"
                            Tag="">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <i:InvokeCommandAction Command="{Binding SelectView}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=RadioButton}}" />
                                i:EventTrigger>
                            i:Interaction.Triggers>
                        RadioButton>
                        <RadioButton
                            Width="200"
                            Height="50"
                            Content="实时数据"
                            FontSize="18"
                            Foreground="White"
                            Style="{DynamicResource RadioButtonMenuStyle}"
                            Tag="">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <i:InvokeCommandAction Command="{Binding SelectView}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=RadioButton}}" />
                                i:EventTrigger>
                            i:Interaction.Triggers>
                        RadioButton>
                        <RadioButton
                            Width="200"
                            Height="50"
                            Content="连接PLC"
                            FontSize="18"
                            Foreground="White"
                            Style="{DynamicResource RadioButtonMenuStyle}"
                            Tag="">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="Checked">
                                    <i:InvokeCommandAction Command="{Binding ConnCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=RadioButton}}" />
                                i:EventTrigger>
                            i:Interaction.Triggers>
                        RadioButton>
                        <TextBlock
                            FontSize="25"
                            Foreground="White"
                            Text="{Binding MyUshort1}" />
                    StackPanel>
                Grid>
            Border>
            
            <Grid Grid.Column="1">
                <ToggleButton
                    x:Name="toggleButton"
                    Width="30"
                    Height="30"
                    Margin="10,20"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Top"
                    Panel.ZIndex="99"
                    Content=""
                    FontSize="20"
                    Foreground="White"
                    Style="{DynamicResource ToggleButtonStyle}" />
                <ContentControl x:Name="container" Content="{Binding MyContent}" />
            Grid>

        Grid>
    Grid>
mah:MetroWindow>

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Kx.Service.Entry;
using Kx.Service.Service.Impl;
using Kx.View;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Kx.ViewModel
{
    public class MyMainViewModel: ObservableRecipient
    {
        public MyMainViewModel()
        {

        }
        public MyMainViewModel(SqlSugarHelper helper, IndexView1 indexView1, IndexView2 indexView2, IndexView3 indexView3,MyS7Entry myS7Entry)
        {
            this.helper = helper;
            this.indexView1 = indexView1;
            this.indexView2 = indexView2;
            this.indexView3 = indexView3;
            this.myS7Entry = myS7Entry;
            MyContent = indexView3;
            IsActive = true;

        }

        private SqlSugarHelper helper;
        private MyS7Entry myS7Entry;
        private MyS7Entry myS7test = new MyS7Entry();
        private CancellationTokenSource cts = new CancellationTokenSource();
        private Plc myS7Master = null;
        private bool isConnected;

        private IndexView1 indexView1;
        private IndexView2 indexView2;
        private IndexView3 indexView3;

        private string myIp = "192.168.2.11";

        public string MyIp
        {
            get { return myIp; }
            set { myIp = value; }
        }

        private string myUshort1;

        public string MyUshort1
        {
            get => myUshort1;
            set => SetProperty(ref myUshort1, value,true);
        }


        private object myContent;

        public object MyContent
        {
            get => myContent;
            set => SetProperty(ref myContent, value);
        }




        #region RelayCommand
        public RelayCommand<RadioButton> SelectView =>
            new RelayCommand<RadioButton>((arg) =>
            {
                if (!(arg is RadioButton button)) return;
                if (string.IsNullOrEmpty(button.Content.ToString())) return;

                switch (button.Content.ToString())
                {
                    case "首页":
                        MyContent = indexView3;
                        break;
                    case "页面1":
                        MyContent = indexView1;
                        break;
                    case "物资管理":
                        MyContent = indexView2;
                        break;
                    case "工艺管理":
                        MyContent = indexView3;
                        break;
                    default:
                        break;
                }
            });


        public RelayCommand<RadioButton> ConnCommand =>
            new RelayCommand<RadioButton>((arg) =>
            {
                if (!(arg is RadioButton button)) return;
                if (string.IsNullOrEmpty(button.Content.ToString())) return;

                if (button.Content.ToString() == "连接PLC")
                {
                    if (myS7Master == null)
                    {
                        try
                        {
                            myS7Master = new Plc(CpuType.S71500, myIp, 0, 0);
                            myS7Master.Open();
                        }
                        catch (Exception ex)
                        {
                            myS7Master = null;
                            MessageBox.Show(ex.Message);

                        }
                    }

                    if (myS7Master.IsConnected)
                    {
                        MessageBox.Show("连接成功!");
                        Task.Run(async () =>
                        {
                            while (true)
                            {
                                await Task.Delay(500);
                                myS7test = myS7Master.ReadClass<MyS7Entry>(103, 0);
                                myS7Entry.MyShort1 = myS7test.MyShort1;
                                myS7Entry.MyShort2 = myS7test.MyShort2;
                                myS7Entry.MyShort3 = myS7test.MyShort3;
                                myS7Entry.MyShort4 = myS7test.MyShort4;
                                MyUshort1 = myS7Entry.MyShort1.ToString();
                            }
                        });
                    }
                }

            });
        #endregion




    }
}

表格:

<UserControl
    x:Class="Kx.View.IndexView2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:hc="https://handyorg.github.io/handycontrol"
    xmlns:local="clr-namespace:Kx.View"
    xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:mv="clr-namespace:Kx.ViewModel"
    d:DataContext="{d:DesignInstance mv:Index2ViewModel}"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">

    <UserControl.Resources>
        <Style x:Key="DataGridStyle" TargetType="{x:Type DataGrid}">
            "CellStyle">
                
                    
                
                
                    
                        
                    
                
            
        -->

        <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
            <TextBlock
                Margin="5"
                HorizontalAlignment="Right"
                VerticalAlignment="Center"
                FontFamily="../Fonts/#FontAwesome"
                FontSize="24"
                Tag="新增"
                Text="">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        
                            "IsMouseOver" Value="True">
                                "Cursor" Value="Hand" />
                                "Foreground" Value="Cyan" />
                            
                            "IsMouseOver" Value="False">
                                "Foreground" Value="White" />
                            
                        
                    Style>
                TextBlock.Style>
                <b:Interaction.Triggers>
                    <b:EventTrigger EventName="MouseUp">
                        <b:InvokeCommandAction Command="{Binding OpenAddWindowCommand2}" />
                    b:EventTrigger>
                b:Interaction.Triggers>
            TextBlock>
        StackPanel>


        <Grid Grid.Row="1">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition Height="60" />
            Grid.RowDefinitions>
            <DataGrid
                AlternationCount="2"
                AutoGenerateColumns="False"
                ItemsSource="{Binding ActualDatas}">
                <DataGrid.CellStyle>
                    <Style TargetType="DataGridCell">
                        "HorizontalContentAlignment" Value="Center" />
                        "VerticalContentAlignment" Value="Center" />
                        "Template">
                            
                                "DataGridCell">
                                    "{TemplateBinding Background}">
                                        "Center" VerticalAlignment="Center" />
                                    
                                
                            
                        
                    Style>
                DataGrid.CellStyle>
                <DataGrid.ColumnHeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        "Background" Value="{DynamicResource MahApps.Brushes.ThemeBackground}" />
                        "BorderBrush" Value="{DynamicResource MahApps.Brushes.Gray5}" />
                        "BorderThickness" Value="0,0,0,3" />
                        "Cursor" Value="Hand" />
                        "FontWeight" Value="SemiBold" />
                        "Foreground" Value="{DynamicResource MahApps.Brushes.ThemeForeground}" />
                        "HorizontalContentAlignment" Value="Center" />
                        "Margin" Value="0" />
                        "MinHeight" Value="25" />
                        "MinWidth" Value="0" />
                        "SnapsToDevicePixels" Value="True" />
                    Style>
                DataGrid.ColumnHeaderStyle>
                <DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                        "Background" Value="#F2F2F2" />
                        
                            "ItemsControl.AlternationIndex" Value="1">
                                "Background" Value="#E6E6E6" />
                            
                            "IsMouseOver" Value="True">
                                
                                "Background" Value="#DDA0DD" />
                            
                        
                    Style>
                DataGrid.RowStyle>
                <DataGrid.Columns>
                    <DataGridTextColumn
                        Width="*"
                        Binding="{Binding Id}"
                        Header="编号"
                        IsReadOnly="True" />
                    <DataGridTextColumn
                        Width="*"
                        Binding="{Binding Name}"
                        Header="名称" />
                    <DataGridTextColumn
                        Width="*"
                        Binding="{Binding MyValue}"
                        Header="" />
                    <DataGridTextColumn
                        Width="*"
                        Binding="{Binding Description}"
                        Header="描述" />
                    <DataGridTextColumn
                        Width="*"
                        Binding="{Binding InsertTime}"
                        Header="日期" />
                    <DataGridTextColumn
                        Width="*"
                        Binding="{Binding DataType}"
                        Header="类型" />
                    <DataGridTemplateColumn Header="操作">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock
                                        Margin="5"
                                        HorizontalAlignment="Right"
                                        VerticalAlignment="Center"
                                        FontFamily="../Fonts/#FontAwesome"
                                        FontSize="24"
                                        Tag="修改"
                                        Text="">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                
                                                    "IsMouseOver" Value="True">
                                                        "Cursor" Value="Hand" />
                                                        "Foreground" Value="Green" />
                                                    
                                                    "IsMouseOver" Value="False">
                                                        "Foreground" Value="Black" />
                                                    
                                                
                                            Style>
                                        TextBlock.Style>
                                        <b:Interaction.Triggers>
                                            <b:EventTrigger EventName="MouseUp">
                                                <b:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:IndexView2}, Path=DataContext.EditCommand2}" CommandParameter="{Binding}" />
                                            b:EventTrigger>
                                        b:Interaction.Triggers>
                                    TextBlock>

                                    <TextBlock
                                        Margin="5"
                                        HorizontalAlignment="Right"
                                        VerticalAlignment="Center"
                                        FontFamily="../Fonts/#FontAwesome"
                                        FontSize="24"
                                        Tag="删除"
                                        Text="">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                
                                                    "IsMouseOver" Value="True">
                                                        "Cursor" Value="Hand" />
                                                        "Foreground" Value="Green" />
                                                    
                                                    "IsMouseOver" Value="False">
                                                        "Foreground" Value="Black" />
                                                    
                                                
                                            Style>
                                        TextBlock.Style>
                                        <b:Interaction.Triggers>
                                            <b:EventTrigger EventName="MouseUp">
                                                <b:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:IndexView2}, Path=DataContext.DeleteCommand2}" CommandParameter="{Binding}" />
                                            b:EventTrigger>
                                        b:Interaction.Triggers>
                                    TextBlock>
                                StackPanel>
                            DataTemplate>
                        DataGridTemplateColumn.CellTemplate>
                    DataGridTemplateColumn>
                DataGrid.Columns>
            DataGrid>
            <StackPanel
                Grid.Row="1"
                Margin="5"
                Orientation="Horizontal">
                
                <hc:Pagination
                    Height="50"
                    Margin="30,10,0,0"
                    IsJumpEnabled="True"
                    MaxPageCount="{Binding MaxPageCount}"
                    PageIndex="{Binding PageIndex, Mode=TwoWay}" />
            StackPanel>

            <StackPanel
                Grid.Row="1"
                Margin="5"
                HorizontalAlignment="Right"
                Orientation="Horizontal">
                <TextBlock
                    Margin="40,15,10,10"
                    Style="{DynamicResource CustomTextBlockStyle}"
                    Text="起始时间" />
                <hc:DateTimePicker Margin="10,10,10,10" SelectedDateTime="{Binding MyStartDateTime, Mode=TwoWay}" />
                <TextBlock
                    Margin="20,15,10,10"
                    Style="{DynamicResource CustomTextBlockStyle}"
                    Text="结束时间" />
                <hc:DateTimePicker Margin="10,10,20,10" SelectedDateTime="{Binding MyEndDateTime, Mode=TwoWay}" />

                <RadioButton
                    Width="100"
                    Height="50"
                    Command="{Binding QueryCommand}"
                    Content="查询"
                    FontFamily="黑体"
                    FontSize="20"
                    Foreground="White"
                    Style="{DynamicResource RadioButtonMenuStyle}"
                    Tag="" />

            StackPanel>
        Grid>
    Grid>
UserControl>

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using Kx.Service.Entry;
using Kx.Service.Service.Impl;
using Kx.View.ViewWindow;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Kx.Service.Service;

namespace Kx.ViewModel
{
    public class Index2ViewModel : ObservableRecipient, IRecipient<PropertyChangedMessage<string>>
    {

        public Index2ViewModel()
        {
                
        }

        public Index2ViewModel(IActualDataService service, AddIndex2WindowViewModel addWindowViewModel)
        {
            this.service = service;
            this.addWindowViewModel = addWindowViewModel;
            IsActive = true;


            //List actualDatas = new List();
            //for (int i = 0; i < 200; i++)
            //{
            //    MyDataType myDataType;
            //    if (i % 2 == 0)
            //    {
            //        myDataType = MyDataType.Float;
            //    }
            //    else if (i % 3 == 0)
            //    {
            //        myDataType = MyDataType.Short;
            //    }
            //    else if (i % 5 == 0)
            //    {
            //        myDataType = MyDataType.Double;
            //    }
            //    else
            //    {
            //        myDataType = MyDataType.String;
            //    }
            //    var item = new ActualData()
            //    {
            //        Name = $"测试名字{i}",
            //        MyValue = $"测试值{i + 1}",
            //        CreateTime = DateTime.Now,
            //        InsertTime = DateTime.Now,
            //        Description = $"测试描述{i + 4}",
            //        DataType = myDataType

            //    };
            //    actualDatas.Add(item);

            //}
            //helper.Db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(ActualData));
            //helper.Db.Insertable(actualDatas).ExecuteCommand();


            //ActualDatas = new ObservableCollection(helper.Db.Queryable().Where(x=>x.Isdeleted!=true).ToPageList(1, pageSize, ref totalNumber));
            ActualDatas = new ObservableCollection<ActualData>(service.GetAllActualDatasPageList(1, pageSize, ref totalNumber));
            MaxPageCount = (int)Math.Ceiling((double)totalNumber / pageSize);
            
            }

        private const int pageSize = 18;
        private int totalNumber;
        private AddIndex2WindowView addWindowView;
        private readonly IActualDataService service;
        private AddIndex2WindowViewModel addWindowViewModel;

        private int pageNum;
        public int PageNum
        {
            get => pageNum; 
            set => SetProperty(ref pageNum, value,true);
        }

        private ObservableCollection<ActualData> actualDatas;

        public ObservableCollection<ActualData> ActualDatas
        {
            get => actualDatas;
            set => SetProperty(ref actualDatas, value);
        }

        //public ObservableCollection ActualDatas { get; set; } = new ObservableCollection();

        private int maxPageCount;

        public int MaxPageCount
        {
            get => maxPageCount;
            set => SetProperty(ref maxPageCount, value);
        }


        private int pageIndex;
        /// 
        /// 点击按钮翻页
        /// 
        public int PageIndex
        {
            get { return pageIndex; }
            set
            {
                bool a = SetProperty(ref pageIndex, value);
                if (a)
                {
                    GotoPage(value);
                }
            }
        }

        private DateTime myStartDateTime;
        public DateTime MyStartDateTime
        {
            get { return myStartDateTime; }
            set { SetProperty(ref myStartDateTime, value); }
        }

        private DateTime myEndDateTime;
        public DateTime MyEndDateTime
        {
            get { return myEndDateTime; }
            set { SetProperty(ref myEndDateTime, value); }
        }

        public RelayCommand QueryCommand =>
            new RelayCommand(() =>
            {
                if (MyEndDateTime < MyStartDateTime)
                {
                    MessageBox.Show("起始时间不能小于结束时间");
                    return;
                }

                
                //如果查询的最大页数MaxPageCount 小于当前页PageNum,则当前页退到最大页数 自动实现了
                //if (PageNum > MaxPageCount)
                //{
                //    PageNum = MaxPageCount;
                //}

                //ActualDatas = new ObservableCollection(this.helper.Db.Queryable()
                //    .Where(x =>
                //    (x.Isdeleted != true)
                //    && x.InsertTime > MyStartDateTime
                //    && x.InsertTime < MyEndDateTime)
                //    .ToPageList(PageNum, pageSize, ref totalNumber));
                ActualDatas = new ObservableCollection<ActualData>(this.service
                    .GetAllActualDatasPageListByTime(PageNum, pageSize, ref totalNumber, MyStartDateTime, MyEndDateTime));
                MaxPageCount = (int)Math.Ceiling((double)totalNumber / pageSize);
            });

        /// 
        /// 打开新页面,新增数据
        /// 
        public RelayCommand OpenAddWindowCommand2 =>
            new RelayCommand(() =>
            {
                addWindowView = new AddIndex2WindowView(addWindowViewModel);
                addWindowView.ShowDialog();

            });
        /// 
        /// 改
        /// 
        public RelayCommand<object> EditCommand2 =>
        new RelayCommand<object>((arg) =>
        {
            if (!(arg is ActualData model)) return;
            int id = this.ActualDatas.FirstOrDefault(t => t.Id == model.Id).Id;

            //int count = helper.Db.Updateable(model).ExecuteCommand();
            int count = this.service.UpdateByModel(model);
            GotoPage(this.pageNum);

            if (count > 0)
            {
                MessageBox.Show("修改成功!");
            }
        });
        /// 
        /// 逻辑删除
        /// 
        public RelayCommand<object> DeleteCommand2 =>
            new RelayCommand<object>((arg) =>
            {
                if (arg is not ActualData model) return;
                int id = this.ActualDatas.FirstOrDefault(t => t.Id == model.Id).Id;
                //int count = helper.Db.Deleteable().In(id).IsLogic().ExecuteCommand();
                int count = this.service.DeleteById(id);
                //ActualDatas = new ObservableCollection(helper.Db.Queryable().Where(x => x.Isdeleted != true).ToPageList(pageNum, pageSize, ref totalNumber));
                ActualDatas = new ObservableCollection<ActualData>(this.service.GetAllActualDatasPageList(pageNum, pageSize, ref totalNumber));
                if (count > 0)
                {
                    MessageBox.Show("删除成功!");
                }
            });



        /// 
        /// 直接输入页数,翻页命令
        /// 
        public RelayCommand<string> GotoPageCommand
        {
            get
            {
                return new RelayCommand<string>((arg) =>
                {
                    GotoPage(int.Parse(arg));
                });
            }
        }


        /// 
        /// 递归函数,翻页
        /// 
        /// 当前页数,控件传进来/查询传进来
        void GotoPage(int pageNum)
        {
            if (MyEndDateTime > MyStartDateTime)
            {
                this.pageNum = pageNum;

                //ActualDatas = new ObservableCollection(this.helper.Db.Queryable()
                //    .Where(x =>
                //    (x.Isdeleted != true)
                //    && x.InsertTime > MyStartDateTime
                //    && x.InsertTime < MyEndDateTime)
                //    .ToPageList(pageNum, pageSize, ref totalNumber));

                ActualDatas = new ObservableCollection<ActualData>(this.service
                    .GetAllActualDatasPageListByTime(pageNum, pageSize, ref totalNumber, MyStartDateTime, MyEndDateTime));

                MaxPageCount = (int)Math.Ceiling((double)totalNumber / pageSize);
                //ActualDatas.CollectionChanged += (o, e) =>
                //{
                //    GotoPage(pageNum);
                //};
            }

            else
            {
                this.pageNum = pageNum;
                //EmployeesDisplay = new(employees.Skip((pageNum - 1) * pageSize).Take(pageSize));

                //ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true && x.InsertTime > DateTime.Now.AddDays(-10)).ToPageList(pageNum, pageSize, ref totalNumber));
                //ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true ).ToPageList(pageNum, pageSize, ref totalNumber));

                ActualDatas = new(this.service.GetAllActualDatasPageList(pageNum, pageSize, ref totalNumber));
                MaxPageCount = (int)Math.Ceiling((double)totalNumber / pageSize);
                //ActualDatas.CollectionChanged += (o, e) =>
                //{
                //    GotoPage(pageNum);
                //};
            }

        }

        
        //接收消息,必须是引用类型。
        public void Receive(PropertyChangedMessage<string> message)
        {
            if (message.Sender is AddIndex2WindowViewModel vm)
            {
                //MessageBox.Show("传送成功!222");
                if (MyEndDateTime > MyStartDateTime)
                {
                    //ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true && x.InsertTime > MyStartDateTime).ToPageList(pageNum, pageSize, ref totalNumber));

                    ActualDatas = new(this.service.GetAllActualDatasPageListByStartTime(pageNum, pageSize, ref totalNumber, MyStartDateTime, MyEndDateTime));
                    MaxPageCount = (int)Math.Ceiling((double)totalNumber / pageSize);
                    //ActualDatas.CollectionChanged += (o, e) =>
                    //{
                    //    ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true && x.InsertTime > MyStartDateTime).ToPageList(pageNum, pageSize, ref totalNumber));
                    //};
                }
                else
                {

                    //ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true && x.InsertTime > DateTime.Now.AddDays(-10)).ToPageList(pageNum, pageSize, ref totalNumber));
                    //ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true).ToPageList(pageNum, pageSize, ref totalNumber));
                    ActualDatas = new(this.service.GetAllActualDatasPageList(pageNum, pageSize, ref totalNumber));
                    MaxPageCount = (int)Math.Ceiling((double)totalNumber / pageSize);

                    //ActualDatas.CollectionChanged += (o, e) =>
                    //{
                    //    //ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true && x.InsertTime > DateTime.Now.AddDays(-10)).ToPageList(pageNum, pageSize, ref totalNumber));
                    //    ActualDatas = new(this.helper.Db.Queryable().Where(x => x.Isdeleted != true).ToPageList(pageNum, pageSize, ref totalNumber));
                    //};
                }
            }
        }
    }
}

你可能感兴趣的:(wpf)