public NewItemViewModel( INavigationService navigationService, ISafeMessagingCenter messagingCenter) { Item = new Item { Text = "Item name", Description = "This is an item description." }; SaveCommand = new SafeCommand(SaveAsync); async Task SaveAsync() { messagingCenter.Send(this, "AddItem", Item); await navigationService.PopAsync(); }; CancelCommand = new SafeCommand(CancelAsync); async void CancelAsync() => await navigationService.PopAsync(); }
//ZM: Built-in dependency injection will resolve these services public ItemsViewModel( INavigationService navigationService, IDataStore <Item> dataStore, ISafeMessagingCenter messagingCenter) { Title = "Browse"; //ZM: Note how we can avoid async-void-lamdas (async () => ) by // using SafeMessagingCenter and SafeCommand // Unhandled exceptions are also caught and handled in app.cs messagingCenter.Subscribe <NewItemViewModel, Item>(this, "AddItem", SaveNewItemAsync); async Task SaveNewItemAsync(NewItemViewModel vm, Item item) { Items.Add(item); await dataStore.AddItemAsync(item); }; //ZM: Because we're extending ViewModelBase, the IsBusy property // will be set to true while LoadItemsCommand is running. // Alot of code is saved avoiding writing a t-c-f block with // IsBusy condition LoadItemsCommand = new SafeCommand( LoadItemsAsync , viewModel: this); //NB to use OneWay Binding in RefreshView async Task LoadItemsAsync() => Items.ReplaceRange(await dataStore.GetItemsAsync(true)); //ZM: An example of page navigation AddItemCommand = new SafeCommand(AddItemAsync); async Task AddItemAsync() => await navigationService.PushAsync <NewItemViewModel>(); //ZM: Passing the data Item to the navigated ViewModel is easy OnItemSelectedCommand = new SafeCommand <Item>(OnItemSelectedAsync); async Task OnItemSelectedAsync(Item item) => await navigationService.PushAsync <ItemDetailViewModel, Item>(item); }
public ComponentWithMessagingDependency(ISafeMessagingCenter messagingCenter) { _messagingCenter = messagingCenter; _messagingCenter.Subscribe <ComponentWithMessagingDependency>(this, "test", dependency => Console.WriteLine("test")); }