这是我的.xml文件-listview的一部分,其中标签从API获取数据。当我单击一项时,我需要获取其“标题”和/或“日期”的值。
ListView x:Name="listViewStories" Margin="12,0,12,0">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label x:Name="titleOfStory"
Text="{Binding Title}"
TextColor="Black"
FontSize="20"
WidthRequest="180">
</Label>
<Label x:Name="dateOfStory"
Text="{Binding Date}"
TextColor="Black"
FontSize="20"
WidthRequest="180"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
这是我的.cs文件,我仅以DisplayAlert代码为例,以便获取值,我尝试了其他方法,但找不到解决方法:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ReadYourPastPage : ContentPage
{
HttpClient client = new HttpClient();
string _ID;
public ReadYourPastPage(string id)
{
InitializeComponent();
_ID = id;
GetStories();
listViewStories.ItemTapped += ListViewStories_ItemTapped;
}
private void ListViewStories_ItemTapped(object sender, ItemTappedEventArgs e)
{
DisplayAlert("I need here to show Title or Date ->", e.Item.ToString() , "Cancel");
}
public async void GetStories()
{
var response = await client.GetStringAsync(returnJSON.GetURL() +
"index.php?IDuser=" + _ID +
"&getStories");
var stories = JsonConvert.DeserializeObject<List<Story>>(response);
listViewStories.ItemsSource = stories;
}
}
答案 0 :(得分:0)
ItemTapped
和ItemSelected
事件使您返回与当前Listview单元格关联的绑定上下文。我建议使用ItemSelected
事件而不是ItemTapped
。在这种情况下,您可以使用以下代码获取对象:
private void ListViewStories_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
// This line null checks the object and also gives you a reference
if (e.SelectedItem is Story story)
{
DisplayAlert($"Title -> {story.Title} Date -> {story.Date}", "Cancel");
// Deselect the cell that was tapped
listViewStories.SelectedItem = null;
}
}
您无法在后面的.cs代码中引用ViewCell
。您只能访问绑定上下文