Last active
December 5, 2019 09:13
-
-
Save icebeam7/1b1ee08ad13c9ff9ad935f9a2cba55eb to your computer and use it in GitHub Desktop.
HarryPotterApp: CharactersListViewModel.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Windows.Input; | |
using System.Threading.Tasks; | |
using System.Collections.ObjectModel; | |
using HarryPotterApp.Models; | |
using Xamarin.Forms; | |
namespace HarryPotterApp.ViewModels | |
{ | |
public class CharactersListViewModel : BaseViewModel | |
{ | |
private ObservableCollection<CharacterViewModel> _characters; | |
public ObservableCollection<CharacterViewModel> Characters | |
{ | |
get { return _characters; } | |
set { _characters = value; OnPropertyChanged(); } | |
} | |
private CharacterViewModel _selectedCharacter; | |
public CharacterViewModel SelectedCharacter | |
{ | |
get { return _selectedCharacter; } | |
set { _selectedCharacter = value; OnPropertyChanged(); } | |
} | |
public ICommand SearchByNameCommand { private set; get; } | |
public ICommand GoToDetailsCommand { private set; get; } | |
public ICommand AddNewCharacterCommand { private set; get; } | |
public INavigation Navigation { get; set; } | |
public CharactersListViewModel(INavigation navigation) | |
{ | |
Navigation = navigation; | |
SearchByNameCommand = new Command<string>(async (name) => await LoadData(name)); | |
GoToDetailsCommand = new Command<Type>(async (pageType) => await GoToDetails(pageType)); | |
AddNewCharacterCommand = new Command<Type>(async (pageType) => await AddNewCharacter(pageType)); | |
} | |
async Task LoadData(string name) | |
{ | |
Characters = new ObservableCollection<CharacterViewModel>(); | |
var hpCharacters = string.IsNullOrWhiteSpace(name) | |
? await App.Context.GetItemsAsync<HPCharacter>() | |
: await App.Context.FilterItemsAsync<HPCharacter>("HPCharacter", $"name LIKE '%{name}%'"); | |
foreach (var item in hpCharacters) | |
Characters.Add(new CharacterViewModel(item)); | |
} | |
async Task GoToDetails(Type pageType) | |
{ | |
if (SelectedCharacter != null) | |
{ | |
var page = (Page)Activator.CreateInstance(pageType); | |
page.BindingContext = new CharacterDetailsViewModel(SelectedCharacter); | |
await Navigation.PushAsync(page); | |
SelectedCharacter = null; | |
} | |
} | |
async Task AddNewCharacter(Type pageType) | |
{ | |
SelectedCharacter = null; | |
var page = (Page)Activator.CreateInstance(pageType); | |
page.BindingContext = new CharacterDetailsViewModel(new CharacterViewModel()); | |
await Navigation.PushAsync(page); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment