![](/img/trans.png)
[英]How to get ListView's ViewCell data and send it to another page in Xamarin.Forms
[英]Is there any way to have a double click event on Listview and send list data to another page in Xamarin Forms
這就是我現在所做的,因為我無法將ID
發送到另一個頁面。 命令參數出現錯誤,為 null 引用異常。
Xaml:
<ListView x:Name="studentListView" ItemsSource="{Binding .} ">
<ListView.ItemTemplate >
<DataTemplate >
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding StudentID}"></Label>
<Label Text="{Binding FirstName}"></Label>
<Label Text="{Binding LastName}"></Label>
<Label Text="{Binding Gender}"></Label>
<Label Text="{Binding Age}"></Label>
<Label Text="{Binding Class}"></Label>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1" Tapped="TapGestureRecognizer_Tapped" CommandParameter="{Binding StudentID}"/>
<TapGestureRecognizer NumberOfTapsRequired="2" Tapped="TapGestureRecognizer_Tapped_1"/>
</StackLayout.GestureRecognizers>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
C# 驗證碼如下:
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
TapGestureRecognizer tapGesture = sender as TapGestureRecognizer;
int clubid = (int) tapGesture.CommandParameter;
Navigation.PushAsync(new StudentPage(clubid));
}
也可以直接在Label
的StudentID上添加一個TapGestureRecognizer
,然后獲取ID值發送到另一個Page。 以下是供您參考的代碼:
學生頁面 Xaml:
<ListView x:Name="studentListView" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding StudentID}" WidthRequest="100" >
<Label.GestureRecognizers >
<TapGestureRecognizer NumberOfTapsRequired="2" Tapped="TapGestureRecognizer_Tapped">
</TapGestureRecognizer>
</Label.GestureRecognizers>
</Label>
<Label Text="{Binding FirstName}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
后端代碼:
public StudentList()
{
InitializeComponent();
studentListView.ItemsSource = new List<MyStudent>
{
new MyStudent{StudentID="1", FirstName="Steve"},
new MyStudent{StudentID="2", FirstName="Lorence"}
};
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
//get the StudentID and pass it through constructor
var s = (sender as Label).Text;
Navigation.PushModalAsync(new MainPage(s));
}
然后,在另一個頁面通過Constructor獲取StudentID
。
public MainPage(string a)
{
InitializeComponent();
App.Current.MainPage.DisplayAlert("Student Id is", a, "OK");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.