Updating DetailPage

Finally, we will need to update how the map on DetailPage is being bound to the data in the DetailViewModel. Since the ViewModel is being initialized via the navigation service now, it happens after the page is constructed, and therefore the map doesn't have the data it needs. Normally, this would not be a problem thanks to data binding; however, since the map control does not allow for data binding, we will need to handle its data differently. The best way for the page to check when its ViewModel has data for its map control is to handle the ViewModel's PropertyChanged event. If the ViewModel's Entry property changes, the map control should be updated accordingly, as shown in the following steps:

  1. First, move the two statements that plot and center the coordinates on the map control out of the constructor and into a separate private method named UpdateMap in the DetailPage class:
      public partial class DetailPage : ContentPage
{
// ...

public DetailPage()
{
InitializeComponent();

BindingContext = new DetailViewModel(DependencyService.Get<INavService>());
}

void UpdateMap()
{
if (_vm.Entry == null)
{
return;
}

// Center the map around the log entry's location
map.MoveToRegion(MapSpan.FromCenterAndRadius(
new Position(_vm.Entry.Latitude,
_vm.Entry.Longitude),
Distance.FromMiles(.5)));


// Place a pin on the map for the log entry's location
map.Pins.Add(new Pin
{
Type = PinType.Place,
Label = _vm.Entry.Title,
Position = new Position(_vm.Entry.Latitude, _vm.Entry.Longitude)
});
}
}
  1. Next, handle the ViewModel's PropertyChanged event to update the map when the ViewModel's Entry property is changed:

      public partial class DetailPage : ContentPage
{
// ...

public DetailPage()
{
// ...
}

void UpdateMap()
{
// ...
}

void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == nameof(DetailViewModel.Entry))
{
UpdateMap();
}
}

protected override void OnAppearing()
{
base.OnAppearing();

if (_vm != null)
{
_vm.PropertyChanged += OnViewModelPropertyChanged;
}
}

protected override void OnDisappearing()
{
base.OnDisappearing();

if (_vm != null)

{
_vm.PropertyChanged -= OnViewModelPropertyChanged;
}
}
}
..................Content has been hidden....................

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