今天跟大家分享的是大麥UWP客戶端,在分類、訂單或是搜索時都用到的一個小技巧,技術粗糙大神勿噴。
以大麥分類舉例,默認打開的時候,會為用戶展示20條數據,當用戶滾動鼠標或者使用手勢將列表滑動到倒數第二行的位置時,自動加載后續20條數據。提高啟動速度的同時稍稍節省用戶的流量。
其他的就不說了,直接進入代碼階段。
Step1,界面部分很簡單,我放棄了Gridvew自己的滾動,在外面包上了一個ScrollViewr,監聽ViewChanged事件(這樣代碼比較簡單,直接用GridView內部的數據變化那種方式,必須給GridView一個高度等等,麻煩)
<ScrollViewer x:Name="scrollRoot" VerticalScrollBarVisibility="Hidden" ViewChanged="scrollRoot_ViewChanged" Margin="10,0">
<GridView>
……
</GridView>
</ScrollViewer/>
Step2,修改綁定界面的ViewModel,增加一個同樣結構的列表屬性,但是要使用ObservableCollection,利用這個集合的可變性以及自動通知界面,方便的動態通知列表,有數據更新。
using System.Collections.Generic; using System.Collections.ObjectModel; namespace Damai.Windows10.App { /// <summary> /// 搜索頁面ViewModel /// </summary> public class SearchViewModel { private List<SearchResultModel> _l; /// <summary> /// 項目列表 /// </summary> public List<SearchResultModel> l { get { return _l; } set { _l = value; if (_l == null) return; if (list == null) list = new ObservableCollection<SearchResultModel>(); foreach (var item in _l) { list.Add(item); } } } /// <summary> /// 用於數據綁定列表 /// </summary> public ObservableCollection<SearchResultModel> list { get; set; } } }
Step3,接下來該怎么初始化,怎么查詢第一波數據(當然了,這個需要咱們服務器端的同學支持,如果他接口不允許分頁查詢,咱們做客戶端的也沒轍 ),初始化數據以后,在當前頁面保存住這個ViewModel,並把它綁定到GridView控件上。
// 加載數據 private async Task<bool> LoadData() { try {
// 你自己的業務邏輯
// 獲取數據並展示 _searchViewModel = new SearchViewModel(); _searchViewModel = await HttpConnectionTool.GetDataEntity<SearchViewModel>(TempDataInfo.MakeApiURL(url)); if (_searchViewModel == null || _searchViewModel.l == null || _searchViewModel?.l?.Count <= 0) { // 異常數據處理 } // 綁定數據(一定綁定是那個ObservableCollection屬性的列表) gridViewProject.ItemsSource = _searchViewModel.list; // 加載完成后,觸發事件 return true; } catch (Exception ex) { return false; } }
Step4,處理鼠標滾動事件
// 滾動至底部動態加載數據 private async void scrollRoot_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e) { if (scrollRoot.VerticalOffset == _originHeight) return; _originHeight = scrollRoot.VerticalOffset; if (_isLoding) return; if (scrollRoot.VerticalOffset <= scrollRoot.ScrollableHeight - 500) return; if (_currentPage >= _countPage + 1) return; _isLoding = true; await Task.Factory.StartNew(async () => { //調用UI線程添加數據 await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { // 拼接業務查詢URL // 查詢新數據
SearchViewModel tempViewModel = await HttpConnectionTool.GetDataEntity<SearchViewModel>(TempDataInfo.MakeApiURL(url)); if (tempViewModel != null && tempViewModel.l != null) _searchViewModel.l = tempViewModel.l; _isLoding = false; }); }); }
好了,搞定打完收工!