这是我启动Xamarin.Forms以来的第二个项目。基本上,我想做的是列出用户手机中的所有联系人,一旦用户从列表中选择了一个联系人,我就想把用户发送到另一个页面上做一些其他操作。
目前,我已经成功地将所有联系人放入ListView,而且我知道如何将用户路由到另一个页面。但问题是,当点击ViewCell时,我不知道如何获取它内部的数据。
目前这是我正在使用的代码,
主页.xaml
<ContentPage.Content>
<StackLayout>
<SearchBar x:Name="filterText"
HeightRequest="40"
Text="{Binding SearchText}" />
<ListView x:Name="lstvv" ItemSelected="lstvv_ItemSelected" ItemsSource="{Binding FilteredContacts}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10"
Orientation="Horizontal">
<Image Source="{Binding Image}"
VerticalOptions="Center"
x:Name="image"
Aspect="AspectFit"
HeightRequest="60"/>
<StackLayout VerticalOptions="Center">
<Label x:Name="lblname" Text="{Binding Name}"
FontAttributes="Bold">
</Label>
<Label Text="{Binding PhoneNumbers[0]}"/>
<Label Text="{Binding Emails[0]}"/>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
主页.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage(IContactsService contactService)
{
BindingContext = new MainViewModel(contactService);
InitializeComponent();
}
private async void lstvv_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
await DisplayAlert("Alert", e.SelectedItem.ToString(), "Ok");
}
}
这是DisplayAlert
如何在ViewCell 中获取数据
这就是字面意思e.SelectedItem
是什么-它是选定的Contact
,您只需要将其投射为
private async void lstvv_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var contact = (Contact)e.SelectedItem;
await DisplayAlert("Alert", contact.Name, "Ok");
}