【问题标题】:get object on ListView Tappedevent在 ListView Tappedevent 上获取对象
【发布时间】:2018-04-25 20:42:14
【问题描述】:

我有一个从 SQLite DB 填充的列表视图。对于那个 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,并将该对象发送到名为ViewSaved 的新视图。

不幸的是,我的变量 calculation 仍然为空,当我将空对象发送到我的新视图时出现异常。

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

【问题讨论】:

  • 请显示单元格的相关代码/xaml 及其绑定
  • 我已经更新了我的问题
  • 当你调试这个时,viewCellSelected 会返回为空吗?
  • ViewCellSelected 返回为 null yes

标签: c# listview xamarin xamarin.forms


【解决方案1】:

不要将Tapped 处理程序放在ViewCell 上,而是使用ListView's ItemTappedItemSelected 方法

void Handle_ItemTapped(object sender, ItemTappedEventArgs e)
    {
      var item = (Calculation)i.Item;
    }

【讨论】:

  • 感谢您的回答,它完成了工作!您能否详细说明其中的区别?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
相关资源
最近更新 更多