首页 > 解决方案 > Xamarin - 点击时如何从列表视图中的 ImageCell 获取数据绑定字符串值?

问题描述

我对 Xamarin 还很陌生,我在弄清楚如何获取图像单元格的绑定值时遇到了问题。

我有一个使用 ImageCell 的列表视图,如下所示,iv'e 将 itemSelected 命令设置为名为“selectedBox_Tapped”的列表视图

    <Grid>
        <ListView x:Name="itemListView" ItemSelected="selectedBox_Tapped">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ImageCell Text="{Binding Name}"
                        Detail="{Binding Compound}"
                               ImageSource="defaultImage.png">
                    </ImageCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>

在后面的 C# 代码中,我正在尝试这个

    private async void selectedBox_Tapped(object sender, ItemTappedEventArgs args)
    {
        string name = ????

        await Navigation.PushAsync(new DetailsPage(name));
    }

我希望能够从 ImageCell 中获取 {Binding Name} 的字符串值,然后将其作为构造函数传递给我的 DetailsPage,如上所示。

其中字符串名称 = ???? 我无法弄清楚我需要做什么才能完成这项工作。

谢谢您的帮助 :)

标签: c#listviewxamarinxamarin.formsxamarin.android

解决方案


利用ItemTappedEventArgs

private async void selectedBox_Tapped(object sender, ItemTappedEventArgs args)
{
    // args.Item will be the context of the tapped cell
    // you will need to cast it to the correct class
    var item = (MyClass)args.Item;

    // once item is cast, you can just refer to its properties
    await Navigation.PushAsync(new DetailsPage(item.Name));
}

推荐阅读