如何以Xamarin表单中的ListView删除项目



我有一个listView,我想删除一些项目,我还没有找到一个有用的答案。

这是Xmal:

<ListView.ItemTemplate >
  <DataTemplate>
    <ViewCell>
      <StackLayout>
        <Label Text="{Binding Name}" 
               Style="{DynamicResource ListItemTextStyle}" />
        <Label Text="{Binding PhoneNo}" 
               Style="{DynamicResource ListItemDetailTextStyle}"/>
      </StackLayout>
    </ViewCell>
  </DataTemplate>
</ListView.ItemTemplate>
</ListView>

和ListView:

public ObservableCollection<Contact> ContactList2 { get; set; }

我可以轻松添加它,但是我不知道如何删除它。

使用上下文菜单

xaml

<ViewCell.ContextActions>
  <MenuItem Clicked="OnDelete" CommandParameter="{Binding .}"
           Text="Delete" IsDestructive="True" />
</ViewCell.ContextActions>

背后的代码
public void OnDelete (object sender, EventArgs e) {
    var mi = ((MenuItem)sender);
    Contact contact = (Contact)mi.CommandParameter;
    ContactList2.Remove(contact);
}

最新更新