2017-02-18 154 views
0

我正在添加一些引腳到地圖,當用戶點擊這個引腳(實際上是引腳的內容),我想打開一個特定的頁面。我可以將參數傳遞給Xamarin中的Clicked事件嗎?

我想要做這樣的事情:

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); 
    } 
} 

但我不知道這是否是可能的參數傳遞給OnPinClicked功能。那可能嗎?如果不是,我能做些什麼來解決這個問題?

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

+1

有關閉,請參閱我的回答後問EDIT部分 –

回答

1

您無法將參數傳遞給事件處理程序。

您可以Pin類寫的包裝(裝飾):

public class PinDecorator 
{ 
    public int Index {get; set;} 
    public Pin Pin {get; set;} 
} 

然後在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); 
    } 
} 

而且你的點擊處理程序:

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

    if (pinDecorator != null) 
    { 
     await Navigation.PushAsync(new MyPage(pinDecorator.Index)); 
    } 
} 

OR

您可以通過另一種方式分配處理程序:

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

AFTER問題編輯:

有一個閉合。您應該創建新變量並在處理程序中使用它。

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

非常感謝@Roma。使用'newIndex'就像一個魅力。 – KelvinS

+0

@KelvinSalton,你是welcone –

0

您可以直接使用EventHandler短編碼版本,它在你的情況是一樣的東西叫OnPinClicked創建:

pin.Clicked += async (sender, args) => 
{ 
    await Navigation.PushAsync(new MyPage(places[index])); 
}; 
+0

謝謝@Zroq。試圖這樣做時,我收到以下錯誤消息:''await'操作符只能在其包含的lambda表達式使用'async'修飾符標記時使用。 – KelvinS

+0

對不起,更新了答案。 – Zroq

+0

謝謝。現在它編譯,但如果我點擊一個引腳,該應用程序崩潰,並出現以下錯誤消息:'索引超出範圍。必須是非負數且小於集合的大小。參數名稱:index' – KelvinS

相關問題