WPF分页写法(MVVM实现)

TODO:萌新劝退,以下正文(举例,具体参照代码)

  1. 新建一个基类,实现双向通知(绑定)
  2. public class PropertyChangedBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            protected void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            protected bool SetProperty(ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null)
            {
                if (EqualityComparer.Default.Equals(backingStore, value))
                    return false;
    
                backingStore = value;
                onChanged?.Invoke();
                NotifyPropertyChanged(propertyName);
                return true;
            }
        }

     

  3. 建立SSviewModel继承PropertyChangedBase
  4. public class SSViewModel : PropertyChangedBase
    {
            /// 
            /// 历史数据列表(选中的设备)
            /// 
            public ObservableCollection CheckHisDataList { get; set; }
    
            private int selectHisCurrentIndex;
            /// 
            /// 页码变更事件
            /// 
            public int SelectHisCurrentIndex
            {
                get => selectHisCurrentIndex; set => SetProperty(ref selectHisCurrentIndex, value, "", () =>
                {
                    GetHisData(SelectHisStartTime, SelectHisEndTime, selectHisCurrentIndex, SelectHisInterval, SelectHisStandard);
                });
            }
            
            /// 
            /// 获取历史数据函数
            /// 委托(将函数委托) 以方便在SSviewModel中调用
            /// 
            public Action GetHisData { get; set; }
    }
    

    TODO:逻辑实现

  5.   //Todo:以下业务实现
    
            /// 
            /// 全局变量
            /// 
            SSViewModel sSView = null;
    
            /// 
            /// 获取服务器数据
            /// 
            /// 开始时间
            /// 结束时间
            /// 页码
            /// 间隔
            /// 只显示超标 默认false
            private async void GetHisData(DateTime start, DateTime end, int page, int interval, bool standard)
            {
                #region 判断是否跨月,并是否支持跨月查询
                if (start > end)
                {
                    MessageBoxX.Show("开始时间不能大于结束时间。", "警 告", MessageBoxIcon.Warning);
                    return;
                }
                var handler = PendingBoxX.Show("加载服务器数据,请稍等(1/2)...", "Processing", false, Application.Current.MainWindow);
                await Task.Run(() =>
                {
                    #region 业务执行
                    var authenticationHeaderValue = new AuthenticationHeaderValue("bearer", CacheExt.GetCache("AccessToken"));
                    _client.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
                    List> param = new List>();
                    param.Add(new KeyValuePair("tabName", $"datalog{start.ToString("yyyyMM")}"));
                    var res = Client.Post("/api/system/GetCanRequest", _client, new FormUrlEncodedContent(param));
                    if (int.Parse(res["data"].ToString()) != 1)
                    {
                        //不支持跨月。判断时间是否跨月
                        if (start.Month != end.Month && start.Year != end.Year)
                        {
                            MessageBoxX.Show("当前用户不支持跨月查询", "警 告", MessageBoxIcon.Warning);
                            return;
                        }
                        else
                        {
                            param = new List>();
                            param.Add(new KeyValuePair("tabName", $"datalog{start.ToString("yyyyMM")}"));
                            param.Add(new KeyValuePair("deviceNo", $"{sSView.SelectedDeviceNo.ToString()}"));
                            param.Add(new KeyValuePair("startTime", $"{start.ToString("yyyy-MM-dd HH:mm:ss")}"));
                            param.Add(new KeyValuePair("endTime", $"{end.ToString("yyyy-MM-dd HH:mm:ss")}"));
                            param.Add(new KeyValuePair("interVal", $"{interval}"));
                            param.Add(new KeyValuePair("standArd", $"{standard}"));
                            var hisList = Client.Post("/api/data/PostHisDataList", _client, new FormUrlEncodedContent(param));
                            curveList.Clear();
                            curveList = hisList.HisDatas;
                            curveCount = hisList.HisDataCount;
                            if (hisList.HisDatas.Any())
                                SetList(hisList.HisDatas, hisList.HisDataCount, page);
                            else
                            {
                                MessageBoxX.Show("没有数据或查询失败", "警 告", MessageBoxIcon.Warning);
                                return;
                            }
                        }
                    }
                    else
                    {
                        //直接请求数据
                        param = new List>();
                        param.Add(new KeyValuePair("tabName", $"datalog{start.ToString("yyyyMM")}"));
                        param.Add(new KeyValuePair("deviceNo", $"{sSView.SelectedDeviceNo.ToString()}"));
                        param.Add(new KeyValuePair("startTime", $"{start.ToString("yyyy-MM-dd HH:mm:ss")}"));
                        param.Add(new KeyValuePair("endTime", $"{end.ToString("yyyy-MM-dd HH:mm:ss")}"));
                        param.Add(new KeyValuePair("interVal", $"{interval}"));
                        param.Add(new KeyValuePair("standArd", $"{standard}"));
                        var hisList = Client.Post("/api/data/PostHisDataList", _client, new FormUrlEncodedContent(param));
                        curveList.Clear();
                        curveList = hisList.HisDatas;
                        curveCount = hisList.HisDataCount;
                        if (hisList.HisDatas.Any())
                            SetList(hisList.HisDatas, hisList.HisDataCount, page);
                        else
                        {
                            MessageBoxX.Show("没有数据或查询失败", "警 告", MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    #endregion
                });
                handler.UpdateMessage("正在完成,后续数据即将推送(2/2)。");
                handler.Close();
                #endregion
            }
    
          //TODO:调用了SetList函数(此处函数更新UI)
    
            /// 
            /// 设置数据列表
            /// 
            /// 
            /// 
            private ObservableCollection SetList(List hisDatas, HisDataCount count, int page)
            {
                #region 统计
                sSView.CheckHiss = new SSViewModel.CheckHis()
                {
                    HisCount = count.Counts.ToString(),
                    HisTemp = $"{(count.MaxTemp / 10.0).ToString("f1")} / {(count.MinTemp / 10.0).ToString("f1")}",
                    HisHumi = $"{(count.MaxHumi / 10.0).ToString("f1")} / {(count.MinHumi / 10.0).ToString("f1")}",
                    HisAvg = $"{(count.AvgTemp / 10.0).ToString("f1")} / {(count.AvgHumi / 10.0).ToString("f1")}"
                };
                //总页数
                sSView.SelectHisTotalIndex = (hisDatas.Count + 500 - 1) / 500;
                #endregion
                hisDatas = hisDatas.Skip((page - 1) * 500).Take(500).ToList();
                //清空
                Dispatcher.Invoke(() =>
                {
                    sSView.CheckHisDataList.Clear();
                });
                foreach (var item in hisDatas)
                {
                    SSViewModel.CheckHisData viewModel = new SSViewModel.CheckHisData()
                    {
                        Deviceno = item.DeviceNO,
                        DataTime = item.DataTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        Humi = item.Humidity / 10.0,
                        Temp = item.Temperature / 10.0,
                        Standard = item.alarmstatus == 1 ? "超标" : ""
                    };
                    Dispatcher.Invoke(() =>
                    {
                        sSView.CheckHisDataList.Add(viewModel);
                    });
                }
                return sSView.CheckHisDataList;
            }
    
    
          //在此页面构造函数中将函数委托给SSviewModel
          sSView.GetHisData = GetHisData;  //此处

    思路逻辑如下:

  6. 要通过MVVM实现分页,关键在页码变更的时候通知后台变更数据
  7. 页码变更事件在SSviewModel里面,我们不能跨页面调用函数。所以此处用到了委托
  8. 实现效果图WPF分页写法(MVVM实现)_第1张图片

你可能感兴趣的:(.Net,Core,wpf)