简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM