Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xamarin.forms ListView ItemSelected

I have a question regarding the ItemSelected() event on a ListView element.

My ListView is based on a DataTemplate like this:

<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="0.5*"/>
                    <ColumnDefinition Width="0.5*"/>
                </Grid.ColumnDefinitions>
                <Label Text="{Binding Name}" FontAttributes="Bold" />
                <Button Text="More" Clicked="MoreInfo" c="{Binding Name}"/>
            </Grid>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

Which gets an Array of PlaceItems which is structured below.

private PlaceItem[] places = {
    new PlaceItem("Theo's huis"),
    new PlaceItem("Kerk op de berg"),
    new PlaceItem("Hostel Stay Okay")
};

public class PlaceItem
    {
        public PlaceItem(string Name, double Lat = 0.0, double Lng = 0.0)
        {
            this.Name = Name;
            this.Lat = Lat;
            this.Lng = Lng;
        }

        public string Name { get; set; }
        public string Location { get; set; }
        public double Lat { get; set; }
        public double Lng { get; set; }
    }

This is my SelectedItem() method:

placesListView.ItemSelected += (object sender, SelectedItemChangedEventArgs e) =>
{
    DisplayAlert("ItemSelected", e.SelectedItem.ToString(), "Ok");
};

When I select an item it always alerts with the string "KK2.PlaceItem" where KK2 is my namespace. So how do I send data to the ItemSelected event from the ListView Item? Like sending the Item index in the Array, or sending the Lat or Lng properties from the object.

I hope that I gave you enough information to help me with this problem. Xamarin is new for me but I'm willing to learn it.

Thanks in advance.

Theo

like image 373
Theo Bouwman Avatar asked Sep 26 '16 15:09

Theo Bouwman


1 Answers

placesListView.ItemSelected += (object sender, SelectedItemChangedEventArgs e) =>
{
    var item = (PlaceItem) e.SelectedItem;

    // now you can reference item.Name, item.Location, etc

    DisplayAlert("ItemSelected", item.Name, "Ok");
};
like image 106
Jason Avatar answered Nov 15 '22 09:11

Jason