【问题标题】:How to get ListView's ViewCell data and send it to another page in Xamarin.Forms如何获取 ListView 的 ViewCell 数据并将其发送到 Xamarin.Forms 中的另一个页面
【发布时间】:2021-02-26 07:25:21
【问题描述】:

这是我开始 Xamarin.Forms 以来的第二个项目。基本上我要做的是列出用户移动设备中的所有联系人,一旦用户从列表中选择一个联系人,我想将用户发送到另一个页面以执行其他操作。

目前我成功地将所有联系人放入 ListView,我也知道如何将用户路由到另一个页面。但问题是我不知道如何在点击 ViewCell 时获取数据。

目前这是我正在使用的代码,

MainPage.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>

MainPage.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");
        }
    }

And this is the DisplayAlert

【问题讨论】:

    标签: c# listview xamarin.forms


    【解决方案1】:

    如何获取ViewCell里面的数据

    这是字面意思是什么e.SelectedItem - 它是选定的Contact,你只需要投射它

    private async void lstvv_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var contact = (Contact)e.SelectedItem;
        await DisplayAlert("Alert", contact.Name, "Ok");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 2021-12-04
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2017-12-07
      相关资源
      最近更新 更多