简体   繁体   中英

How to delete item from ListView in Xamarin forms

I have a ListView and I want to delete some items, I have not found a useful answer yet.

this is a 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>

and listview :

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

I can easily add it, but I do not know how to delete it.

Use a context menu

XAML

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

code behind

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM