ViewModel层:ResultPageViewModel
依赖一:mvvmlightlibs
viewmodel可被单元测试
- ResultPageViewModel.cs—公开变量
/// <summary>
/// 正在载入。
/// </summary>
public const string Loading = "正在载入";
/// <summary>
/// 没有满足条件的结果。
/// </summary>
public const string NoResult = "没有满足条件的结果";
/// <summary>
/// 没有更多结果。
/// </summary>
public const string NoMoreResult = "没有更多结果";
/// <summary>
/// 一次显示的诗词数量。
/// </summary>
public const int PageSize = 20;
//不手写字符串,用常量表示
无限滚动(Infinite Scrolling)
依赖二:Xamarin.Forms.Extended.InfiniteScrolling(打开预览版)
创建模板方法:扩展->Resharper->Tools->Templates Explorer->This computer c#->New Template
- ResultPageViewModel.cs—Infinite Scrolling
/// <summary>
/// 诗词集合。
/// </summary>
public InfiniteScrollCollection<Poetry> PoetryCollection { get; }
//在构造函数里初始化InfiniteScrollCollection
/// <summary>
/// 加载状态。
/// </summary>
public string Status {
get => _status;
set => Set(nameof(Status), ref _status, value);
}
/// <summary>
/// 加载状态。
/// </summary>
private string _status;
/// <summary>
/// 查询语句。
/// </summary>
public Expression<Func<Poetry, bool>> Where {
get => _where;
set
{
Set(nameof(Where), ref _where, value);
}
}
/// <summary>
/// 查询语句。
/// </summary>
private Expression<Func<Poetry, bool>> _where;
/// <summary>
/// 能否加载更多结果。
/// </summary>
private bool _canLoadMore;
/// <summary>
/// 诗词存储。
/// </summary>
private IPoetryStorage _poetryStorage;
/// <summary>
/// 搜索结果页ViewModel。
/// </summary>
/// <param name="poetryStorage">诗词存储。</param>
public ResultPageViewModel(IPoetryStorage poetryStorage) {
_poetryStorage = poetryStorage;
PoetryCollection = new InfiniteScrollCollection<Poetry>();
PoetryCollection.OnCanLoadMore = () => _canLoadMore; //判断是否还能继续加载
PoetryCollection.OnLoadMore = async () => {
Status = Loading; //设置状态为Loading
var poetries =
await poetryStorage.GetPoetriesAsync(Where,
PoetryCollection.Count, PageSize);
//调用GetPoetriesAsync()获得诗词集合
//PoetryCollection里有多少条就跳过这些有的继续加载,返回页面PageSize个
Status = string.Empty;
if (poetries.Count < PageSize)
{//当poetries的数量不足PageSize,不能再加载更多了
_canLoadMore = false;
Status = NoMoreResult;
}
if (PoetryCollection.Count == 0 && poetries.Count == 0)
{//集合里和查询结果都为0时,没有满足条件的结果
Status = NoResult;
}
return poetries;
};
//当OnCanLoadMore()函数返回值为true时,自动调用OnLoadMore()
//开始从数据库中读数据
}
因为xamarin只有在页面显示时会有事件触发,所以添加页面显示命令。
/// <summary>
/// 页面显示命令。
/// </summary>
public RelayCommand _pageAppearingCommand;
/// <summary>
/// 页面显示命令。
/// </summary>
public RelayCommand PageAppearingCommand =>
_pageAppearingCommand ?? (_pageAppearingCommand =
new RelayCommand(async () =>
await PageAppearingCommandFunction()));
public async Task PageAppearingCommandFunction() {
PoetryCollection.Clear();
_canLoadMore = true; //数据加载进来时将_canLoadMore设置为true(不然一直为false)
await PoetryCollection.LoadMoreAsync();
}