分享大麦UWP版本开发历程-03.GridView或ListView 滚动底部自动加载后续数据
今天跟大家分享的是大麥UWP客戶端,在分類、訂單或是搜索時都用到的一個小技巧,技術(shù)粗糙大神勿噴。
以大麥分類舉例,默認(rèn)打開的時候,會為用戶展示20條數(shù)據(jù),當(dāng)用戶滾動鼠標(biāo)或者使用手勢將列表滑動到倒數(shù)第二行的位置時,自動加載后續(xù)20條數(shù)據(jù)。提高啟動速度的同時稍稍節(jié)省用戶的流量。
其他的就不說了,直接進(jìn)入代碼階段。
Step1,界面部分很簡單,我放棄了Gridvew自己的滾動,在外面包上了一個ScrollViewr,監(jiān)聽ViewChanged事件(這樣代碼比較簡單,直接用GridView內(nèi)部的數(shù)據(jù)變化那種方式,必須給GridView一個高度等等,麻煩)
<ScrollViewer x:Name="scrollRoot" VerticalScrollBarVisibility="Hidden" ViewChanged="scrollRoot_ViewChanged" Margin="10,0"><GridView>
……
</GridView>
</ScrollViewer/>
Step2,修改綁定界面的ViewModel,增加一個同樣結(jié)構(gòu)的列表屬性,但是要使用ObservableCollection,利用這個集合的可變性以及自動通知界面,方便的動態(tài)通知列表,有數(shù)據(jù)更新。
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>/// 用于數(shù)據(jù)綁定列表/// </summary>public ObservableCollection<SearchResultModel> list { get; set; }} }Step3,接下來該怎么初始化,怎么查詢第一波數(shù)據(jù)(當(dāng)然了,這個需要咱們服務(wù)器端的同學(xué)支持,如果他接口不允許分頁查詢,咱們做客戶端的也沒轍 ),初始化數(shù)據(jù)以后,在當(dāng)前頁面保存住這個ViewModel,并把它綁定到GridView控件上。
// 加載數(shù)據(jù)private async Task<bool> LoadData(){try{// 你自己的業(yè)務(wù)邏輯
// 獲取數(shù)據(jù)并展示 _searchViewModel = new SearchViewModel();_searchViewModel = await HttpConnectionTool.GetDataEntity<SearchViewModel>(TempDataInfo.MakeApiURL(url));if (_searchViewModel == null || _searchViewModel.l == null || _searchViewModel?.l?.Count <= 0){// 異常數(shù)據(jù)處理} // 綁定數(shù)據(jù)(一定綁定是那個ObservableCollection屬性的列表)gridViewProject.ItemsSource = _searchViewModel.list;// 加載完成后,觸發(fā)事件 return true;}catch (Exception ex){ return false;}}
Step4,處理鼠標(biāo)滾動事件
// 滾動至底部動態(tài)加載數(shù)據(jù)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 () =>{//調(diào)用UI線程添加數(shù)據(jù)await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>{// 拼接業(yè)務(wù)查詢URL// 查詢新數(shù)據(jù)SearchViewModel tempViewModel = await HttpConnectionTool.GetDataEntity<SearchViewModel>(TempDataInfo.MakeApiURL(url));if (tempViewModel != null && tempViewModel.l != null) _searchViewModel.l = tempViewModel.l;_isLoding = false;});});}
好了,搞定打完收工!
?
轉(zhuǎn)載于:https://www.cnblogs.com/Damai-Pang/p/5209093.html
總結(jié)
以上是生活随笔為你收集整理的分享大麦UWP版本开发历程-03.GridView或ListView 滚动底部自动加载后续数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用SQL语句添加删除修改字段
- 下一篇: 学军中学推理社2017届招新试题