在ListView Tappedevent上获取对象

我有一个从SQLite数据库填充的列表视图。对于该listview,构造了一种方法,用于在敲击listview元素时进行处理:


xaml单元格:


<ListView x:Name="CalculationListview" ItemsSource="{Binding Calculation}" HasUnevenRows="true" IsPullToRefreshEnabled="true" Refreshing="Handle_Refreshing">

    <ListView.ItemTemplate>

        <DataTemplate>

            <ViewCell Tapped="Handle_Tapped">

                <ViewCell.ContextActions>

                    <MenuItem Text="Delete" IsDestructive="True" Clicked="Handle_Clicked" />

                </ViewCell.ContextActions>

                <StackLayout>

                    <Label Text="{Binding Qty}">

                    </Label>

                    <Label Text="{Binding Note}">

                    </Label>

                    <Label Text="{Binding Id}">

                    </Label>

                </StackLayout>

            </ViewCell>

        </DataTemplate>

    </ListView.ItemTemplate>

</ListView>

C#


async void Handle_Tapped(object sender, System.EventArgs e)

{

    var viewCellSelected = sender as MenuItem;

    var calculation = viewCellSelected?.BindingContext as Calculation;


    var page = new ViewSaved(calculation);

    await Navigation.PushModalAsync(page);

}

如您所见,我想Calculation从给定的listview元素中检索对象并将该对象发送到名为的新视图ViewSaved。


不幸的是,我的变量calculation仍然为null,并且在将空对象发送到新视图时收到异常。


我怀疑这sender as MenuItem;是问题所在。


翻阅古今
浏览 150回答 1
1回答

慕哥6287543

而不是将Tapped处理程序放在上ViewCell,请使用ListView's ItemTapped或ItemSelected方法void Handle_ItemTapped(object sender, ItemTappedEventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; var item = (Calculation)i.Item;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP