Updating MainViewModel

In order to move the navigation functionality from MainPage to MainViewModel, we will need to add two new Command properties—one for creating a new log entry and another for viewing the details of an existing log entry:

      public class MainViewModel : BaseViewModel
{
// ...

Command<TripLogEntry> _viewCommand;
public Command<TripLogEntry> ViewCommand
{
get
{
return _viewCommand
?? (_viewCommand = new Command<TripLogEntry>(async (entry) => await ExecuteViewCommand(entry)));
}
}

Command _newCommand;
public Command NewCommand
{
get
{
return _newCommand
?? (_newCommand = new Command(async () => await ExecuteNewCommand()));
}
}

async Task ExecuteViewCommand(TripLogEntry entry)
{
await NavService.NavigateTo<DetailViewModel, TripLogEntry>(entry);
}

async Task ExecuteNewCommand()
{
await NavService.NavigateTo<NewEntryViewModel>();
}

// ...
}

With the Command properties in place on MainViewModel, we can now update MainPage to use these commands instead of using the Xamarin.Forms navigation service directly from the page:

  1. Create a private MainViewModel property named _vm in the MainPage class that simply provides access to the page's BindingContext, but is casted as a MainViewModel:
      public class MainPage : ContentPage
{
MainViewModel _vm
{
get { return BindingContext as MainViewModel; }
}

// ...
}
  1. Replace the Navigation.PushAsync method call in the ItemTapped event handler for the entries ListView with a call to the ViewCommand:
      void Trips_ItemTapped(object sender, ItemTappedEventArgs e) 
{
var trip = (TripLogEntry)e.Item;
_vm.ViewCommand.Execute(trip);

trips.SelectedItem = null;
};
  1. Replace the Clicked attribute on the New ToolbarItem element with a Command attribute whose value is a binding to the NewCommand:
      <ToolbarItem Text="New" Command="{Binding NewCommand}" />
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.79.121