XAMARIN使用menuItem从列表视图中删除项目

时间:2018-12-03 08:54:38

标签: listview xamarin

我正在尝试使用menuItem在Listview中删除一个项目。但是似乎无法删除该项目。谁能看出什么错?我在menuItem中绑定错误吗?

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.ContextActions>
                            <MenuItem Clicked="MenuItem_Clicked" Text="Delete" IsDestructive="true" CommandParameter="{Binding .}" />
                        </ViewCell.ContextActions>
                        <StackLayout>
                            <Label Text="{Binding Product}"></Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>

xaml.cs

  private void MainPicker_SelectedIndexChanged(object sender, EventArgs e)
        {
            // feedback popup box
             var product = MainPicker.Items[MainPicker.SelectedIndex];
             DisplayAlert(product, "Layer added to calculation list", "OK");
            // if selected add to list          
            if (null != product)
            {
                LayersClass layer = new LayersClass();
                layer.Product = product;
                listProducts.Add(layer);
            }        
        }

        private void MenuItem_Clicked(object sender, EventArgs e)
        {
            var menuItem = ((MenuItem)sender);
            var product = ( TYPE?)menuItem.CommandParameter; //unsure of type 

            listProducts.Remove(layer);
        }

1 个答案:

答案 0 :(得分:0)

已解决:

 private async void MenuItem_Clicked(object sender, EventArgs e)
        {
            var menuItem = ((MenuItem)sender);           
            var answer = await DisplayAlert("Are you sure?", null, "Yes", "No");

            if (answer)
            {
                listProducts.Remove((LayersClass)menuItem.CommandParameter);
            }
        }