Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind to Xamarin.Forms.Maps.Map from ViewModel

I'm working on a Xamarin.Forms app using a page that displays a map. The XAML is:

<maps:Map x:Name="Map">
    ...
</maps:Map>

I know that the map can be accessed from the page's code-behind like this:

var position = new Position(37.79762, -122.40181);
Map.MoveToRegion(new MapSpan(position, 0.01, 0.01));
Map.Pins.Add(new Pin
{
    Label = "Xamarin",
    Position = position
});

But because this code would break the app's MVVM architecture, I'd rather like to access the Map object from my ViewModel, not directly from the View/page - either using it directly like in the above code or by databinding to its properties.

Does anybody know a way how this can be done?

like image 335
Thomas Weller Avatar asked Jan 22 '15 20:01

Thomas Weller


1 Answers

If you don't want to break the MVVM pattern and still be able to access your Map object from the ViewModel then you can expose the Map instance with a property from your ViewModel and bind to it from your View.

Your code should be structured like described here below.

The ViewModel:

using Xamarin.Forms.Maps;

namespace YourApp.ViewModels
{
    public class MapViewModel
    {
        public MapViewModel()
        {
            Map = new Map();
        }

        public Map Map { get; private set; }
    }
}

The View (in this example I'm using a ContentPage but you can use whatever you like):

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourApp.Views.MapView">
    <ContentPage.Content>
                <!--The map-->
                <ContentView Content="{Binding Map}"/>
    </ContentPage.Content>
</ContentPage>

I didn't show how, but the above code snipped can only work when the ViewModel is the BindingContext of your view.

like image 69
Aquablue Avatar answered Sep 28 '22 05:09

Aquablue