public class ContextViewModel: INotifyPropertyChanged { ContextDataStore DataStore =new ContextDataStore(); ObservableCollection<ContextModel> Items { get; set; } Command LoadItemsCommand { get; set; } public event PropertyChangedEventHandler PropertyChanged; private int page = 1; private int rows = 10; 初始化各种数据与监听 ContextViewModel() { Items = new ObservableCollection<ContextModel>(); LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand()); //监听添加的消息 MessagingCenter.Subscribe<ContextModelPage, ContextModel>(, async (obj, item) => { var _item = item as ContextModel; var date = await DataStore.AddItemAsync(_item); if (date) { LoadDate(); , , ); await obj.Navigation.PopAsync(); } else { , , ); } }); //监听更新的消息 MessagingCenter.Subscribe<ContextModelPage, ContextModel>(, async (obj, item) => { var date = await DataStore.UpdateItemAsync(item); if (date) { LoadDate(); , , ); await obj.Navigation.PopAsync(); } else { , , ); } }); ExecuteLoadItemsCommand(); } 删除的方法 Task<bool> DeleteItem(int id) { var date = await DataStore.DeleteItemAsync(id); if (date) { var item = Items.Where(a => a.ID == id).FirstOrDefault(); Items.Remove(item); OnPropertyChanged(); } return date; } 加载数据的命令 Task ExecuteLoadItemsCommand() { try { items = await DataStore.GetItemsAsync(page,rows); foreach (var item in items) { Items.Add(item); } OnPropertyChanged(); page++; } catch (Exception ex) { } } 重新刷新数据 LoadDate() { Items.Clear(); page = 1; var items = await DataStore.GetItemsAsync(page, rows); foreach (var item in items) { Items.Add(item); } OnPropertyChanged(); page++; } OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
嗯.还是说明一下 这个ViewModel就类似于MVC中的控制器,起到一个承上启下的作用.与页面交互并把这些交互信息传递给仓储,由仓储来访问WebAPI
5.编写界面,绑定数据我们创建一个ContentPage页面如下:
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:DemoApp.HTTPClientDemo.ViewModels" xmlns:Controls="clr-namespace:DemoApp.HTTPClientDemo;" x:ClassControls:MyListView VerticalOptions="FillAndExpand" HasUnevenRows="true" LoadMoreCommand x:Name LineBreakMode="NoWrap" Style FontSize LineBreakMode="NoWrap" Style FontSize
这个ContentPage中,我们使用了StackLayout布局,ListView,ToolbarItem 等控件.绑定了我们前面编写的ContextViewModel(后台代码绑定的,在下面)
编写这个ContentPage的后台代码如下: