c# - 根据 bindingcontext 删除 ListView item

标签 c# xaml xamarin xamarin.forms

我创建了一个从 SQLite 数据库填充的 ListView 。 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);
}

不幸的是,我不知道如何从我的绑定(bind)上下文中获取对象以便删除该项目。我显然已经准备好点击事件处理程序:

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

最佳答案

上下文操作

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

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

示例截图

此屏幕截图来自 Xamarin.Forms 文档,并未反射(reflect)以下代码。

代码

<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);
}

关于c# - 根据 bindingcontext 删除 ListView item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50027840/

相关文章:

c# - 我的 C# 应用程序在访问 Properties.Settings.Default.workingdirectory 时发出 HTTP 请求

c# - 如何在 Xamarin.Forms 中将参数从一个页面传递到另一个页面?

xamarin - 如何在 Xamarin.Mac 应用程序中查找指向非公共(public)框架的链接

WPF 应用程序在通过 doPDF 打印机打印到文件后引发异常

javascript - 在 Android 6 中将 JavaScript 注入(inject) WebView

c# - JSON.NET 和 nHibernate,在序列化时忽略延迟加载的对象

c# - 在 ASP.NET 中以文本框模式 "date"禁用以前的日期和时间

c# - 在 Windows Phone 上设计媒体播放器的好方法是什么?

c# - WPF。对于多重触发条件, 'Property' 必须具有非空值

wpf - 如何从滚动查看器中的最后一项中删除额外的边距?