0
votes

I'm trying to bind the EventArgs result of a MapLongClicked event to a property "Location" on the ViewModel on Xamarin Forms, using GoogleMaps nuget package. The problem is that I can only access those EventArgs in XAML Code behind. As I'm using MVVMCross, I've found something about field binding, but it's not for code behind. My MapPage looks like this right now:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MapPage : MvxContentPage
{
    public MapPage()
    {
        InitializeComponent();

        map.UiSettings.ZoomControlsEnabled = false;

        map.MapLongClicked += (sender, e) =>
        {
            //((MapViewModel)map.BindingContext).Location = new Microsoft.Azure.Documents.Spatial.Point(e.Point.Longitude, e.Point.Latitude);
            var pin = new Pin
            {
                Type = PinType.SearchResult,
                Position = new Position(e.Point.Latitude, e.Point.Longitude),
                Label = string.Format(e.Point.Latitude.ToString("0.000") + " / " + e.Point.Longitude.ToString("0.000"))
            };
            map.Pins.Add(pin);
        };

    }
}

XAML:

<mvx:MvxContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:mvx="clr-namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
    xmlns:maps="clr-namespace:Xamarin.Forms.GoogleMaps;assembly=Xamarin.Forms.GoogleMaps"
    xmlns:behaviors="clr-namespace:XamFormsMaps.Core.Behaviors;assembly=XamFormsMaps.Core"
    x:Class="XamFormsMaps.Core.Pages.MapPage">
    <ContentPage.Content>
        <StackLayout>
            <maps:Map 
               x:Name="map"
               WidthRequest="320" 
               HeightRequest="200"
               IsShowingUser="true"
               MapType="Hybrid">

                <maps:Map.Behaviors>
                    <behaviors:MapBehavior ItemsSource="{Binding Parkings}" />
                </maps:Map.Behaviors>
            </maps:Map>
        </StackLayout>
    </ContentPage.Content>
</mvx:MvxContentPage>

I've tried the commented option but it's giving me a casting error, so I haven't got more ideas.

Does anyone know how can I send a variable from XAML code behind to a ViewModel?

1
Does the map has a MapLongClicked property on XAML ? - FabriBertani
Yeeees! It does @FabriBertani - CarlosMacMar
did you try bind that property with a command on the viewmodel ? like MapLongClick="{Binding SomeCommand}" - FabriBertani
I've tried but I don't know if it's possible neither how to get the EventArgs from that command on the ViewModel - CarlosMacMar
You get casting error because map.bindingcontext is not MapViewModel? - Luminous_Dev

1 Answers

0
votes

This solved my problem:

((MapViewModel)map.BindingContext).Location = new Microsoft.Azure.Documents.Spatial.Point(e.Point.Longitude, e.Point.Latitude);
        var pin = new Pin

Make sure the map.BindingContext is MapViewModel at runtime.