【问题标题】:How to delete item from ListView in Xamarin forms如何从 Xamarin 表单中的 ListView 中删除项目
【发布时间】:2019-05-06 02:14:58
【问题描述】:

我有一个 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>

和列表视图:

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

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

【问题讨论】:

  • ObservableCollection 有多个删除方法 .Remove(someInstanceoOfContact) .RemoveAt(someInt) 等...
  • 如果您的 ListView 的 ItemSource 等于您的 ObservableCollection,那么通过从您的集合中删除一个项目,它将自动从列表视图中删除(应该实现 inotifypropertychanged)

标签: xamarin


【解决方案1】:

使用context menu

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);
}

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 2019-07-07
    • 2019-03-09
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多