我正试图从aListView中删除项/行,但困难在于我还需要传入一些委托或触发一些事件或其他内容,因此当一个人单击按钮删除该行时,我的代码将处理其他一些逻辑(例如从db中删除项或其他内容)。
我有一个自定义控件:

public class SportsTeam : StackLayout { .. }

在这个控件中,元素之一是aListView,它列出了运动队中的所有人。
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中,或者也可以用代码编写,绑定到项目模板的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);
}

重要提示:这只会从绑定集合中删除项。要从原始列表中删除它,您需要使用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还解释了从alistview中删除的内容。

09-30 14:11
查看更多