如何删除Xamarin跨平台表单中的ListView项
<ViewCell.ContextActions>
<MenuItem Text="Delete" IsDestructive="True" Command="Binding DleteItemCommand}" />
</ViewCell.ContextActions>
但我希望用户代码符合MVVM模式
所以,视图模型只是用于表示层,你需要与你的单元格而不是视图模型进行交互。执行以下步骤:
1。为单元格创建一个ViewModels的Observable集合。2. 将这个集合添加到ListView的ItemSource中。3.然后为命令添加回调方法
<ListView x:Name="citiesListView" ItemTapped="OnSelection">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="DeleteAction" Text="Delete" IsDestructive="true" CommandParameter="{Binding .}" />
</ViewCell.ContextActions>
<StackLayout Padding="15,0">
<Label
Text="{Binding .}"
FontSize="30"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
然后在代码中:
public partial class YourPage : ContentPage
{
public ObservableCollection<string> YourCollection { get; set; }
public YourPage()
{
InitializeComponent();
// initialize at this point
YourCollection = new ObservaleCollection(<Some collection of view models>);
citiesListView.ItemsSource = YourCollection;
}
private void DeleteAction(object sender, System.EventArgs e)
{
var menuItem = ((MenuItem)sender);
var yourViewModel = (YourViewModelType) menuItem.CommandParameter;
YourCollection.Remove(yourViewModel);
}
您可以添加ObservableCollection<YourType>
,并在命令中删除元素。
var collection = new ObservableCollection<YourType>();
yourList.ItemSource = collection;
// in Command
public void OnDelete (object sender, EventArgs e)
{
// getting reference on menu item
var menuItem = ((MenuItem)sender).CommandParameter;
// cast to underlying viewModel
var yourObject = (YourType)menuItem;
collection.Remove(yourObject);
}
是,它与MVVM模式兼容。你在ListView中有一个Cell它是viewModel的一个单一表示。使用它的方法你有下一个关系:"模型-视图模型-视图"。ObservableCollection对你在ListView的单元格中显示的ViewModels有一个引用,现在你可以很容易地删除你想要的单元格。在代码