c# - 根据 bindingcontext 删除 ListView 项
问题描述
我创建了一个从 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);
}
不幸的是,我不知道如何从绑定上下文中获取对象,以便删除该项目。我显然已经有了 clicked 事件处理程序:
void Handle_Clicked(object sender, System.EventArgs e)
{
App.Database.DeleteCalculationAsync(SOMETHING HERE);
}
解决方案
上下文动作
我建议将删除功能移至Context Actions。
当用户在 ViewCell 上从右向左滑动时,上下文操作将出现在 iOS 上,而当用户长按 ViewCell 时,上下文操作将出现在 Android 上。
示例截图
此屏幕截图来自 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);
}
推荐阅读
- python - Django view - template returned as bytestring (b'')
- python - How do I download all pdfs from a website?
- encryption - Best way to encrypt data
- wordpress - 如何在 docker 上的 wordpress 中上传插件?
- c++ - QComboBox:仅在展开时显示图标
- r - input$(variable storage ID) 不工作但 input$(ID) 工作
- php - PHP function to convert Hex to HSL (Not HSL to Hex)
- python - Kedro: How to pass multiple same data from a directory as a node input?
- c++ - How to write values within nested nodes in a OpenCV -based XML FileStorage?
- sql - Laravel 在使用 where 条件和更新时提供不同的结果