Pass object in click/tapped event handler in Xamar

2019-04-22 10:50发布

Here is my job class:

public class Job
{
        public string Id{ get; set;}
        public string Name{ get; set;}
}

And here is my ListView:

public class JobListePage:ContentPage
    {
        // Members
        private ListView lstView;

        // Constructor    
        public JobListePage ()
        {
            // Set members
            lstView = new ListView ();

            // Create job objects
            Job[] jobs = {new Job(){Id="1", Name="Benny"}, new Job(){Id="2", Name="Lukas"}};

            // Fill listview with job objects
            lstView.ItemsSource = jobs;

            // HOW CAN I PASS THE TAPPED OBJECT HERE???
            lstView.ItemTapped += async (o, e) => {
                await DisplayAlert("Tapped",  "HERE I WANT TO SHOW THE ID", "OK");
                ((ListView)o).SelectedItem = null; // de-select the row
            };

            ....

Now how can I pass the tapped "job-object" to the event?

You can see that I show a message to the user. And in there it should stand the ID of the tapped object.

2条回答
虎瘦雄心在
2楼-- · 2019-04-22 11:20

The following page explains exactly what you are looking for: Selecting an Item in a ListView

listView.ItemSelected += async (sender, e) => 
{
    await DisplayAlert("Tapped!", (e.SelectedItem as Job).Id + " was tapped.", "OK");
};

If you want to navigate to a detail page passing arguments then use the following:

listView.ItemSelected += async (sender, e) => 
{       
      var jobPage = new JobPage(e.SelectedItem as Job); // new page shows correct data          
      await Navigation.PushAsync(jobPage);
};
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-22 11:25

try:

        lstView.ItemTapped += async (o, e) => {
            var myList= (ListView)o;
            var myJob = (myList.SelectedItem as Job);
            await DisplayAlert("Tapped",  myJob.Id, "OK");
            myList.SelectedItem = null; // de-select the row
        };
查看更多
登录 后发表回答