C# XAMARIN:我的Listview中有两个标签,我需要在.cs中获取它们的文本,但我无法通过x:Name访问它们
这是我的.xml文件——listview的一部分,标签从API中获取数据。当我单击一个项目时,我需要获取其标题和/或日期的值C# XAMARIN:我的Listview中有两个标签,我需要在.cs中获取它们的文本,但我无法通过x:Name访问它们,c#,xamarin,xamarin.forms,xamarin.android,C#,Xamarin,Xamarin.forms,Xamarin.android,这是我的.xml文件——listview的一部分,标签从API中获取数据。当我单击一个项目时,我需要获取其标题和/或日期的值 ListView x:Name="listViewStories" Margin="12,0,12,0"> <ListView.ItemTemplate> <DataTemplate> <ViewCell>
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>
ListView x:Name=“listViewStories”Margin=“12,0,12,0”>
这是我的.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;
}
}
[XamlCompilation(XamlCompilationOptions.Compile)]
公共部分类ReadYourPastPage:ContentPage
{
HttpClient=新的HttpClient();
字符串_ID;
公共ReadYourPastPage(字符串id)
{
初始化组件();
_ID=ID;
GetStories();
listViewStories.ItemTapped+=listViewStories\u ItemTapped;
}
私有无效列表ViewStories\u ItemTapped(对象发送方,ItemTappedEventArgs e)
{
DisplayAlert(“我需要在这里显示标题或日期->”,例如Item.ToString(),“Cancel”);
}
公共异步void GetStories()
{
var response=await client.GetStringAsync(returnJSON.GetURL())+
“index.php?IDuser=“+”ID+
“&getStories”);
var stories=JsonConvert.DeserializeObject(响应);
listViewStories.ItemsSource=故事;
}
}
点击的itemstapped
和ItemSelected
事件返回与当前Listview单元格关联的绑定上下文。我建议使用ItemSelected
事件,而不是itemstapped
。在这种情况下,您可以使用以下代码获取对象:
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
。您只能访问绑定上下文请不要将代码作为图像发布。欢迎!如果您将代码作为问题中的文本(并确保其格式为代码)发布,而不是作为人们需要花费额外时间转录的图像发布,人们将更容易提供帮助。我编辑了它,谢谢!很抱歉!非常感谢你!几个小时来一直在试图解决这个问题。你是个救生员!非常感谢。