Adding MainViewModel

The main purpose of a ViewModel is to separate the business logic, for example, data access and data manipulation, from the user interface logic. Right now, our MainPage directly defines the list of data that it is displaying. This data will eventually be dynamically loaded from an API but for now, we will move this initial static data definition to its ViewModel so that it can be data bound to the user interface.

In order to create the ViewModel for MainPage, perform the following steps:

  1. Create a new class file in the ViewModels folder and name it MainViewModel.
  2. Update the MainViewModel class to inherit from BaseViewModel:
      public class MainViewModel : BaseViewModel
{
// ...
}
  1. Add an ObservableCollection<T> property to the MainViewModel class and name it LogEntries. This property will be used to bind to the ItemsSource property of the ListView element on MainPage.xaml:
      public class MainViewModel : BaseViewModel
{
ObservableCollection<TripLogEntry> _logEntries;
public ObservableCollection<TripLogEntry> LogEntries
{
get { return _logEntries; }
set
{
_logEntries = value;
OnPropertyChanged ();
}
}

// ...
}
  1. Next, remove the List<TripLogEntry> that populates the ListView element on MainPage.xaml and repurpose that logic in the MainViewModel—we will put it in the constructor for now:
      public MainViewModel()
{
LogEntries = new ObservableCollection<TripLogEntry>();

LogEntries.Add(new TripLogEntry
{

Title = "Washington Monument",
Notes = "Amazing!",
Rating = 3,
Date = new DateTime(2017, 2, 5),
Latitude = 38.8895,
Longitude = -77.0352
});

LogEntries.Add(new TripLogEntry
{

Title = "Statue of Liberty",
Notes = "Inspiring!",
Rating = 4,
Date = new DateTime(2017, 4, 13),
Latitude = 40.6892,
Longitude = -74.0444
});

LogEntries.Add(new TripLogEntry
{

Title = "Golden Gate Bridge",
Notes = "Foggy, but beautiful.",
Rating = 5,
Date = new DateTime(2017, 4, 26),
Latitude = 37.8268,
Longitude = -122.4798
});
}
  1. Set MainViewModel as the BindingContext property for MainPage. Do this by simply setting the BindingContext property of MainPage in its code-behind file to a new instance of MainViewModel. The BindingContext property comes from the Xamarin.Forms.ContentPage base class:
      public MainPage()
{
InitializeComponent();

BindingContext = new MainViewModel();
}
  1. Finally, update how the ListView element on MainPage.xaml gets its items. Currently, its ItemsSource property is being set directly in the Page's code behind. Remove this and instead update the ListView element's tag in MainPage.xaml to bind to the MainViewModel LogEntries property:
      <ListView ... ItemsSource="{Binding LogEntries}">
..................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