加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 基于bindingcontext删除ListView项

发布时间:2020-12-16 01:26:38 所属栏目:百科 来源:网络整理
导读:我创建了一个从SQLite DB填充的列表视图. XML看起来像这样: ListView x:Name="CalculationListview" ItemsSource="{Binding Calculation}" HasUnevenRows="true" ListView.ItemTemplate DataTemplate ViewCell StackLayout Label Text="{Binding Qty}"/Labe
我创建了一个从SQLite DB填充的列表视图. XML看起来像这样:

<ListView x:Name="CalculationListview" ItemsSource="{Binding Calculation}" HasUnevenRows="true">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Label Text="{Binding Qty}"></Label>
                    <Label Text="{Binding Note}"></Label>
                    <Button Text="Delete" Clicked="Handle_Clicked"></Button>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

我已经创建了一个按钮,如果单击该按钮,我想从中删除该项目.

我已经制作了一个从数据库中删除的方法,它接收一个给定的对象.

public Task<int> DeleteCalculationAsync(Calculation calculation)
{
    return database.DeleteAsync(calculation);
}

不幸的是,我不知道如何从bindingcontext中获取对象,以便我可以删除该项目.我显然已经点击了事件处理程序:

void Handle_Clicked(object sender,System.EventArgs e)
{
    App.Database.DeleteCalculationAsync(SOMETHING HERE);
}

解决方法

上下文操作

我建议将删除功能移至Context Actions.

当用户长按ViewCell时,当用户在ViewCell上从右向左滑动时,上下文操作将出现在iOS上.

示例截图

此屏幕截图来自Xamarin.Forms文档,并未反映下面的代码.

<ListView x:Name="CalculationListview" ItemsSource="{Binding Calculation}" HasUnevenRows="true">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.ContextActions>
                    <MenuItem Text="Delete" IsDestructive="True" Clicked="Handle_Delete"/>
                 </ViewCell.ContextActions>
                <StackLayout>
                    <Label Text="{Binding Qty}"></Label>
                    <Label Text="{Binding Note}"></Label>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
async void Handle_Delete(object sender,System.EventArgs e)
{
    var viewCellSelected = sender as MenuItem;
    var calculationToDelete = viewCellSelected?.BindingContext as Calculation;

    await App.Database.DeleteCalculationAsync(calculationToDelete);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读