An alternative way of setting the viewable area of the map is to use the Map
control’s SetView
method. SetView
accepts a LocationRectangle
object, which specifies a rectangular region of the map.
The MapViewModel
contains a LocationRectangle
property that is applied to the map within the viewmodel’s PropertyChanged
event handler, as shown in the following excerpt:
public MapView()
{
var viewModel = new MapViewModel(new RouteCalculator());
viewModel.PropertyChanged += (sender, args) =>
{
switch (args.PropertyName)
{
...
case "LocationRectangle":
LocationRectangle rectangle = ViewModel.LocationRectangle;
if (rectangle != null)
{
map.SetView(ViewModel.LocationRectangle);
}
break;
}
};
...
}
Later in this chapter, you see how the Map
control’s SetView
method is used to pan and zoom to an area of the map to display the shortest path between two points.
Caution
When the lifespan of the viewmodel exceeds that of the view, subscribing to a viewmodel’s PropertyChanged
event from the view can cause a memory leak. This is because the target of an event subscription (in this case the view) is kept alive by the garbage collector while the event source (the viewmodel) exists in memory. To prevent this, you may forgo the use of the PropertyChanged
event in favor of an alternative approach, such as weak events, or a messaging system to communicate with the view, both of which are to be found in various MVVM frameworks including the Calcium SDK project.
The Map control’s ZoomLevel
property allows you to control the altitude of the viewpoint. This property ranges between 0 and 20, with 0 being completely zoomed out so that the entire map is visible, and 20 being zoomed in as close as possible. Unlike the old Bing Maps control, 20 is a hard limit. If you attempt to assign the zoom level to a higher value, an ArgumentOutOfRangeException
is thrown. To demonstrate the ZoomLevel
property of the Map control, the sample view uses a data-binding to the viewmodel’s ZoomLevel
property, as shown:
<m:Map x:Name="map"
...
ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}"
...
</m:Map>
As the user performs pinch and spread gestures, the viewmodel’s ZoomLevel
property is updated.
3.15.221.133