我可以将参数传递给 Xamarin 中的 Clicked 事件吗?

Kel*_*inS 5 c# xamarin xamarin.forms

我正在向地图添加一些图钉,当用户点击此图钉(实际上是图钉的内容)时,我想打开特定页面。

我想做这样的事情:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我不知道是否可以将参数传递给OnPinClicked函数。那可能吗?如果不是,我该怎么做才能解决这个问题?

注意:我是 Xamarin 和 C# 的新手。

mdi*_*666 15

绑定上下文

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

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

// data  = 333;
Run Code Online (Sandbox Code Playgroud)


Rom*_*och 5

您无法将参数传递给事件处理程序。

您可以为Pin类编写包装器(装饰器):

public class PinDecorator
{
    public int Index {get; set;}
    public Pin Pin {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

然后在方法中使用这个类PopulateMap()

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

    pinDecorator.Pin.Clicked += OnPinClicked;

    MyMap.Pins.Add(pinDecorator.Pin);
  }
}
Run Code Online (Sandbox Code Playgroud)

还有你的点击处理程序:

async void OnPinClicked(object sender, EventArgs e)
{
    var pinDecorator = sender as PinDecorator;

    if (pinDecorator != null)
    {
        await Navigation.PushAsync(new MyPage(pinDecorator.Index));
    }
}
Run Code Online (Sandbox Code Playgroud)

或者

您可以通过另一种方式分配处理程序:

var newIndex = index; // for avoiding closure
pin.Clicked += async (s, e) =>
{
    await Navigation.PushAsync(new MyPage(places[newIndex]));
};
Run Code Online (Sandbox Code Playgroud)

问题编辑后:

有一个关闭。您应该创建新变量并在处理程序中使用它。

var newIndex = index;
pin.Clicked += (sender, ea) =>
{
    Debug.WriteLine("Name: {0}", places[newIndex].Name); 
    OnPinClicked(places[newIndex]);
};
Run Code Online (Sandbox Code Playgroud)