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>
            <!--  left  -->
            <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="&#xf1b3;" />
                        <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="&#xf17a;">
                            <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="&#xf1c0;">
                            <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="&#xf187;">
                            <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="&#xf135;">
                            <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="&#xf1b3;">
                            <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="&#xf17c;">
                            <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="&#xf11c;">
                            <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>
            <!--  right  -->
            <Grid Grid.Column="1">
                <ToggleButton
                    x:Name="toggleButton"
                    Width="30"
                    Height="30"
                    Margin="10,20"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Top"
                    Panel.ZIndex="99"
                    Content="&#xf060;"
                    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}">
            <Setter Property="CellStyle">
                <Setter.Value>
                    <Style TargetType="{x:Type DataGridCell}">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="VerticalContentAlignment" Value="Center" />
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="DataGridCell">
                                    <Grid Background="{TemplateBinding Background}">
                                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                                    </Grid>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>

                    </Style>
                </Setter.Value>
            </Setter>
            <Setter Property="ColumnHeaderStyle">
                <Setter.Value>
                    <Style TargetType="{x:Type DataGridColumnHeader}">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                    </Style>
                </Setter.Value>
            </Setter>
            <Setter Property="GridLinesVisibility" Value="None" />
        </Style>
    </UserControl.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Border BorderBrush="#383839" BorderThickness="0,0,0,1">
            <TextBlock
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                FontFamily="黑体"
                FontSize="24"
                Foreground="White"
                Text="增删改查测试" />
        </Border>
        <!--<Border>
            <TextBlock
                Margin="5"
                HorizontalAlignment="Right"
                VerticalAlignment="Center"
                FontFamily="../Fonts/#FontAwesome"
                FontSize="24"
                Tag="新增"
                Text="&#xf055;">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Cursor" Value="Hand" />
                                <Setter Property="Foreground" Value="Cyan" />
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="False">
                                <Setter Property="Foreground" Value="White" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
                <b:Interaction.Triggers>
                    <b:EventTrigger EventName="MouseUp">
                        <b:InvokeCommandAction Command="{Binding OpenAddWindowCommand2}" />
                    </b:EventTrigger>
                </b:Interaction.Triggers>
            </TextBlock>
        </Border>-->

        <StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
            <TextBlock
                Margin="5"
                HorizontalAlignment="Right"
                VerticalAlignment="Center"
                FontFamily="../Fonts/#FontAwesome"
                FontSize="24"
                Tag="新增"
                Text="&#xf055;">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Cursor" Value="Hand" />
                                <Setter Property="Foreground" Value="Cyan" />
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="False">
                                <Setter Property="Foreground" Value="White" />
                            </Trigger>
                        </Style.Triggers>
                    </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">
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="VerticalContentAlignment" Value="Center" />
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="DataGridCell">
                                    <Grid Background="{TemplateBinding Background}">
                                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                                    </Grid>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </DataGrid.CellStyle>
                <DataGrid.ColumnHeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <Setter Property="Background" Value="{DynamicResource MahApps.Brushes.ThemeBackground}" />
                        <Setter Property="BorderBrush" Value="{DynamicResource MahApps.Brushes.Gray5}" />
                        <Setter Property="BorderThickness" Value="0,0,0,3" />
                        <Setter Property="Cursor" Value="Hand" />
                        <Setter Property="FontWeight" Value="SemiBold" />
                        <Setter Property="Foreground" Value="{DynamicResource MahApps.Brushes.ThemeForeground}" />
                        <Setter Property="HorizontalContentAlignment" Value="Center" />
                        <Setter Property="Margin" Value="0" />
                        <Setter Property="MinHeight" Value="25" />
                        <Setter Property="MinWidth" Value="0" />
                        <Setter Property="SnapsToDevicePixels" Value="True" />
                    </Style>
                </DataGrid.ColumnHeaderStyle>
                <DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                        <Setter Property="Background" Value="#F2F2F2" />
                        <Style.Triggers>
                            <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                                <Setter Property="Background" Value="#E6E6E6" />
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="True">
                                <!--  #DBDBDB  -->
                                <Setter Property="Background" Value="#DDA0DD" />
                            </Trigger>
                        </Style.Triggers>
                    </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="&#xf14b;">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                <Style.Triggers>
                                                    <Trigger Property="IsMouseOver" Value="True">
                                                        <Setter Property="Cursor" Value="Hand" />
                                                        <Setter Property="Foreground" Value="Green" />
                                                    </Trigger>
                                                    <Trigger Property="IsMouseOver" Value="False">
                                                        <Setter Property="Foreground" Value="Black" />
                                                    </Trigger>
                                                </Style.Triggers>
                                            </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="&#xf056;">
                                        <TextBlock.Style>
                                            <Style TargetType="TextBlock">
                                                <Style.Triggers>
                                                    <Trigger Property="IsMouseOver" Value="True">
                                                        <Setter Property="Cursor" Value="Hand" />
                                                        <Setter Property="Foreground" Value="Green" />
                                                    </Trigger>
                                                    <Trigger Property="IsMouseOver" Value="False">
                                                        <Setter Property="Foreground" Value="Black" />
                                                    </Trigger>
                                                </Style.Triggers>
                                            </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:TextBox Name="pageNumberName" Width="50"  hc:InfoElement.Placeholder="Page" />
                <Button Content="Go" Margin="5,0,0,0" Command="{Binding EditCommand2}" CommandParameter="{Binding ElementName=pageNumberName, Path=Text}"/>-->
                <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="&#xf002;" />

            </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<ActualData> actualDatas = new List<ActualData>();
            //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<ActualData>(actualDatas).ExecuteCommand();


            //ActualDatas = new ObservableCollection<ActualData>(helper.Db.Queryable<ActualData>().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<ActualData> ActualDatas { get; set; } = new ObservableCollection<ActualData>();

        private int maxPageCount;

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


        private int pageIndex;
        /// <summary>
        /// 点击按钮翻页
        /// </summary>
        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<ActualData>(this.helper.Db.Queryable<ActualData>()
                //    .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);
            });

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

            });
        /// <summary>
        /// 改
        /// </summary>
        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<ActualData>(model).ExecuteCommand();
            int count = this.service.UpdateByModel(model);
            GotoPage(this.pageNum);

            if (count > 0)
            {
                MessageBox.Show("修改成功!");
            }
        });
        /// <summary>
        /// 逻辑删除
        /// </summary>
        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<ActualData>().In(id).IsLogic().ExecuteCommand();
                int count = this.service.DeleteById(id);
                //ActualDatas = new ObservableCollection<ActualData>(helper.Db.Queryable<ActualData>().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("删除成功!");
                }
            });



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


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

                //ActualDatas = new ObservableCollection<ActualData>(this.helper.Db.Queryable<ActualData>()
                //    .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<ActualData>().Where(x => x.Isdeleted != true && x.InsertTime > DateTime.Now.AddDays(-10)).ToPageList(pageNum, pageSize, ref totalNumber));
                //ActualDatas = new(this.helper.Db.Queryable<ActualData>().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<ActualData>().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<ActualData>().Where(x => x.Isdeleted != true && x.InsertTime > MyStartDateTime).ToPageList(pageNum, pageSize, ref totalNumber));
                    //};
                }
                else
                {

                    //ActualDatas = new(this.helper.Db.Queryable<ActualData>().Where(x => x.Isdeleted != true && x.InsertTime > DateTime.Now.AddDays(-10)).ToPageList(pageNum, pageSize, ref totalNumber));
                    //ActualDatas = new(this.helper.Db.Queryable<ActualData>().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<ActualData>().Where(x => x.Isdeleted != true && x.InsertTime > DateTime.Now.AddDays(-10)).ToPageList(pageNum, pageSize, ref totalNumber));
                    //    ActualDatas = new(this.helper.Db.Queryable<ActualData>().Where(x => x.Isdeleted != true).ToPageList(pageNum, pageSize, ref totalNumber));
                    //};
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值