Maui Maps Binding MarkerClicked Event

242 views Asked by At

Im trying to bind a command to the marker clicked event on Maui maps. I have binded pins using a DataTemplate. I can get it to work via the MainPage.xaml.cs but my app is using a viewModel. I can not bind the event.

<maps:Map x:Name="map" IsShowingUser="true" ItemsSource="{Binding SavedSpots}" >               
    <maps:Map.ItemTemplate>
        <DataTemplate>
            <maps:Pin Location="{Binding Location}"
                  Address="{Binding Address}"
                  Label="{Binding Label}"
                  MarkerClicked="{Binding Pin_MarkerClicked}">                        
            </maps:Pin>
        </DataTemplate>
    </maps:Map.ItemTemplate>
</maps:Map>

I have tried the CommunityToolkit EventToCommandBehavior but the map does not have any behaviors.

Any help would be great. Thanks

I have tried all the code that every has suggested. I dont think it can be done that way as it is a field under the Pin.

    namespace Microsoft.Maui.Maps
{
    /// <summary>
    /// Represents a Pin that displays a map.
    /// </summary>
    public interface IMapPin : IElement
    {
        /// <summary>
        /// The physical address that is associated with this pin.
        /// </summary>
        string Address { get; }

        /// <summary>
        /// The label that is shown for this pin.
        /// </summary>
        string Label { get; }

        /// <summary>
        /// The geographical location of this pin.
        /// </summary>
    Location Location { get; }

    object? MarkerId { get; set; }

    bool SendMarkerClick();

    bool SendInfoWindowClick()

;
    }
}

Does anyone know how i can pass this from MainPage.xaml.cs to my MainPageViewModel.cs

 private void Pin_MarkerClicked(object sender, PinClickedEventArgs e)


{   
     var senderpin = (Pin)sender;           
 
 }

Thanks in advance

1

There are 1 answers

2
Guangyu Bai - MSFT On

You can use the EventToCommandBehavior to set the command for the MarkerClicked event.

First, setting the name for the ContantPage.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         ...
         x:Name="this">

Second, you can bind the command in the ViewModel.

<maps:Map.Behaviors>
     <toolkit:EventToCommandBehavior                            
         EventName="MarkerClicked"
         Command="{Binding Source={x:Reference this}, Path=BindingContext.Pin_MarkerClicked}">
     </toolkit:EventToCommandBehavior>               
 </maps:Map.Behaviors>