Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass parameters to a Clicked event in Xamarin?

I am adding some pins to a map, and when the user tap on this pin (actually the content of the pin) I want to open a specific page.

I want to do something like this:

async void OnPinClicked(Places place)
{
  await Navigation.PushAsync(new MyPage(place));
}

private void PopulateMap(List<Places> places)
{
  for (int index = 0; index < places.Count; index++)
  {
    var pin = new Pin
    {
      Type = PinType.Place,
      Position = new Position(places[index].Lat, places[index].Lon),
      Label = places[index].Name,
      Address = places[index].Address
    };

    pin.Clicked += (sender, ea) =>
    {
        Debug.WriteLine("Name: {0}", places[index].Name); // The app is crashing here (if I tap on a pin)
        OnPinClicked(places[index]);
    };

    MyMap.Pins.Add(pin);
  }
}

But I don't know if it is possible to pass parameters to the OnPinClicked function. Is that possible? If it is not, what can I do to solve this?

Note: I'm newbie on Xamarin and C#.

like image 834
KelvinS Avatar asked Feb 18 '17 20:02

KelvinS


People also ask

How do you pass parameters in button click event xamarin forms?

You can't pass arguments to event handlers. You can assign handler by another way: var newIndex = index; // for avoiding closure pin. Clicked += async (s, e) => { await Navigation.


1 Answers

BindingContext

<Button Text="Button1" Clicked="Button1_Clicked" BindingContext="333"/>

string data = ((Button)sender).BindingContext as string;

// data  = 333;
like image 123
mdimai666 Avatar answered Sep 24 '22 02:09

mdimai666