Reputation: 145
Cannot figure out a proper way get an item from ListView.
My XAML bindings:
<ListView x:Name="MyListView" ItemTapped="MyListView_ItemTapped" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Name}"></Label>
<Label Text="{Binding Email}"></Label>
<Image Source="{Binding PhotoUrl}" WidthRequest="20" HeightRequest="20"></Image>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
All the data gets displayed and works fine. Class is called Forums:
[JsonProperty("results")]
public List<Result> Results { get; set; }
public class Result
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("photoUrl")]
public string PhotoUrl { get; set; }
}
I have made MyListView_ItemTapped Function and for now, I'm trying to display its name when the item is tapped on, but not sure what is a proper way to do it. And I always think that I'm just bodging some random things together until I get something.
private void MyListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var index = forums.Results.IndexOf(e.Item as Forums.Result);
DisplayAlert("Alert", forums.Results[index].Name, "OK");
}
So if anyone could point me to the better direction or even give few better examples or just explain how should it be done.
Upvotes: 1
Views: 6182
Reputation: 11
You can also use selected item property
<ListView **SelectedItem="{Binding Result, Mode=TwoWay}">**
code behind:
`private Result _result;
public Result Result
{
get { return _deviceSession; }
set
{
SetProperty(ref _deviceSession, value);
}
}`
From this class object you can able to get all data
Upvotes: 1
Reputation: 7189
You can cast to the correct Class
private void MyListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var index = forums.Results.IndexOf(e.Item as Forums.Result);
var selectedItem = (Forums.Result)e.Item;
if(selectedItem != null)
{
DisplayAlert("Alert", selected|Item.Name, "OK");
}
}
Oh and if you want to remove the selecteditem effect just
if (sender is ListView lv) lv.SelectedItem = null;
Upvotes: 0
Reputation: 89102
just cast e.Item to the correct type
var item = e.Item as Forums.Result;
// then use item.Name, etc...
Upvotes: 2