using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using Muchinfo.PC.Common.Extensions; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace Muchinfo.MTPClient.Infrastructure.DataPager { public abstract class QueryViewModelBase : ViewModelBase { #region Fields private ObservableCollection _dataGridItemsSource; private T _currentDataGridItem; private int _pageSize; private int _pageIndex; private int _itemCount; #endregion #region Properties /// /// DataGrid绑定集合 /// public ObservableCollection DataGridItemsSource { get { return _dataGridItemsSource; } set { Set(() => DataGridItemsSource, ref _dataGridItemsSource, value); } } /// /// DataGrid当前选中项 /// public T CurrentDataGridItem { get { return _currentDataGridItem; } set { Set(() => CurrentDataGridItem, ref _currentDataGridItem, value); } } /// /// 总记录条数 /// public int ItemCount { get { return _itemCount; } set { Set(() => ItemCount, ref _itemCount, value); } } /// /// 每页条数 /// public int PageSize { get { return _pageSize; } set { Set(() => PageSize, ref _pageSize, value); } } /// /// 当前页 /// public int PageIndex { get { return _pageIndex; } set { Set(() => PageIndex, ref _pageIndex, value); } } /// /// 重置命令 /// public RelayCommand ResetCommand { get { return new RelayCommand(Reset); } } private bool isQuery = false; /// /// 查询命令 /// public RelayCommand SearchCommand { get { return new RelayCommand(() => { if (QuerCheck()) { //通过PageIndex触发PagerSearchCommand if (PageIndex == 0) PageIndex = -1; PageIndex = 0; } }, () => { return !isQuery; }); } } /// /// 分页命令 /// public RelayCommand PagerSearchCommand { get { return new RelayCommand(() => Task.Factory.TryStartNew(() => { isQuery = true; if (QuerCheck()) { int totalCount; var result = Query(out totalCount); ItemCount = totalCount; DataGridItemsSource = result.ToObservableCollection(); if (DataGridItemsSource != null && DataGridItemsSource.Any()) { CurrentDataGridItem = DataGridItemsSource[0]; } } isQuery = false; }, () => { isQuery = false; })); } } #endregion #region Constructor protected QueryViewModelBase() { PageSize = 15; RegisterMessage(); } #endregion #region Methods /// /// 查询数据集合 /// /// IEnumerable{`0}. protected abstract IEnumerable Query(out int totalCount); /// /// 查询检查 /// /// true if XXXX, false otherwise. protected virtual bool QuerCheck() { return true; } /// /// 重置查询条件 /// protected virtual void Reset() { } /// /// 初始化 /// protected virtual void Initialize() { Reset(); SearchCommand.Execute(string.Empty); } /// /// 注册消息 /// protected virtual void RegisterMessage() { } #endregion } }