我试图从 ListView
中删除项目/行,但困难在于我还需要传递一些委托(delegate)或触发一些事件或其他东西,所以当一个人点击一个按钮删除该行,我的代码在其他地方处理一些其他逻辑(例如,从数据库中删除该项目或其他任何内容)。
我有一个自定义控件:
public class SportsTeam : StackLayout { .. }
在此控件中,其中一个元素是 ListView
,它列出了运动队中的所有人员。
var viewModel = teamMembers.Select(x => new SportsTeamViewModel(x));
return new ListView
{
HasUnevenRows = true,
ItemSource = viewModel,
ItemTemplate = new DataTemplate(typeof(SportsTeamViewCell));
};
在 SportsTeamViewCell
中,我有以下内容:
private Grid CreateContent()
{
var grid = new Grid();
// Setup row and column definitions.
// Add items to the Grid
grid.Children.Add(...);
var removeButton = RemoveButton;
grid.Children.Add(removeButton);
Grid.SetRowSpan(removeButton, 2);
return grid;
}
private Button RemoveButton
{
get
{
var button = new Button
{
Image = "Icons/remove.png"
};
return button;
}
}
从这里开始,我不知道如何使按钮触发事件或可以通过构造函数传入一些删除,因此针对要删除的单个单元格/行/项目执行一些自定义逻辑被删除。
最佳答案
这是你可以做的:
这是我的模型类:
public class Item
{
public string ItemName { get; set; }
public string ItemDetails { get; set; }
}
在我的 XAML 中,或者您也可以用代码编写,绑定(bind)到项目模板的 Command Parameter
:
<Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked"></Button>
完整的项目模板如下:
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding ItemName}" HorizontalOptions="StartAndExpand" FontSize="30"></Label>
<Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked">
</Button>
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
在你的代码文件中你可以这样做:
public void DeleteClicked(object sender, EventArgs e)
{
var item = (Xamarin.Forms.Button)sender;
Item listitem = (from itm in allItems
where itm.ItemName == item.CommandParameter.ToString()
select itm)
.FirstOrDefault<Item>();
allItems.Remove(listitem);
}
重要:这只会从绑定(bind)集合中删除项目。要从原始列表中删除它,您需要使用 ObservableCollection
这里是解释场景的完整源代码 - Handling Child Control Event in Listview using XAMARIN.FORMS .
还有教程 - How to handle Row selection and delete Button in Row For Custom ListView using Xamarin.Forms也解释从 listview
中删除。
关于c# - 如何从 Xamarin Forms ListView 中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728535/