Page 43 - MSDN Magazine, June 2017
P. 43

Figure 11 Exposing a ViewModel
using Microsoft.WindowsAzure.MobileServices; using MyBookshelf.Authentication;
using MyBookshelf.Model;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices; using System.Threading.Tasks;
using Xamarin.Forms;
namespace MyBookshelf.ViewModel {
public class BookViewModel : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
private bool isBusy; public bool IsBusy {
get {
return isBusy; }
set {
isBusy = value; OnPropertyChanged(); }
}
private bool isUserAuthenticated;
public bool IsUserAuthenticated {
get {
return isUserAuthenticated; }
set {
isUserAuthenticated = value; OnPropertyChanged(); }
}
private string userId;
public string UserId {
get {
return userId; }
set {
userId = value; OnPropertyChanged(); }
}
private ObservableCollection<Book> books;
public ObservableCollection<Book> Books {
get {
return books; }
set {
books = value; OnPropertyChanged(); }
}
private Book selectedBook;
public Book SelectedBook {
get {
return selectedBook; }
set {
selectedBook = value; OnPropertyChanged(); }
}
public BookViewModel() {
this.Books = new ObservableCollection<Book>();
this.IsBusy = false; }
public Command SaveBooks {
get {
return new Command(async () => {
if (IsUserAuthenticated) {
this.IsBusy = true;
await App.DataManager.SaveAsync(this.Books); this.IsBusy = false;
} });
} }
public Command LoadBooks {
get {
return new Command(async () => {
if (IsUserAuthenticated) {
this.IsBusy = true;
var listOfBooks = await App.DataManager.LoadAsync<Book>(UserId); this.Books = new ObservableCollection<Book>(listOfBooks); this.IsBusy = false;
} });
} }
public Command AddNewBook {
get {
return new Command(() =>
this.Books.Add(new Book { UserId = this.UserId }));
} }
public async Task LoginAsync() {
var authenticator = DependencyService.Get<IAuthentication>(); var user = await authenticator.LoginAsync(App.DataManager.Client,
MobileServiceAuthenticationProvider.MicrosoftAccount); if (user == null)
{
IsUserAuthenticated = false;
return; }
else {
UserId = user.UserId; IsUserAuthenticated = true; return;
} }
} }
msdnmagazine.com June 2017 39


















   41   42   43   44   45