Search code examples
windows-phone-7listboxitems

WP7 delete item from listBox via message box


need some help, when i click the tap_event I get a message box delete or cancel which works and the price is taken off the total but it does'nt update the shopping cart after, it crashes on "ListBoxCart.Items.Remove(curr), thanks in advance!

    private void listBoxCart_Tap(object sender, GestureEventArgs e)
    {
        if (MessageBox.Show("Are you sure!", "Delete", MessageBoxButton.OKCancel)
            == MessageBoxResult.OK)
        {

            foreach (Dvd curr in thisapp.ShoppingCart)
            {
                if (curr.Equals(listBoxCart.SelectedItem))
                {
                    listBoxCart.Items.Remove(curr);
                    listBoxCart.SelectedIndex = -1;
                    total -= Convert.ToDecimal(curr.price);

                    NavigationService.Navigate(new Uri("/ShoppingCart.xaml", UriKind.RelativeOrAbsolute));
                }


            }
            txtBoxTotal.Text = total.ToString();
            listBoxCart.ItemsSource = thisapp.ShoppingCart;
        }
        else
        {
            NavigationService.Navigate(new Uri("/ShoppingCart.xaml", UriKind.RelativeOrAbsolute));
        }


    }

Solution

  • I have wrote an artile (sorry in french but you can read the XAML) : http://www.peug.net/2012/05/17/contextmenu-dans-listbox-datatemplate/

    and in the code-behind : an example :

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = sender as MenuItem;
            var fe = VisualTreeHelper.GetParent(menuItem) as FrameworkElement;
            Dvd _fig = fe.DataContext as Dvd;
            thisapp.ShoppingCart.Remove(_fig);
    
            reloading();
        }