Question

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


    }
Was it helpful?

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

OTHER TIPS

When you set the ItemsSource property for the ListBox, it generates a read-only collection and displays them. What you're trying to do is access this read-only collection and modify it but because it's read-only, you can't do that.

Instead you can either have your collection implement the INotifyCollectionChanged interface and raise a collection changed event when the user has deleted the item or use an ObservableCollection instead to store your items. ObservableCollection implements the INotifyCollectionChanged interface for you so you can remove items from the ObservableCollection and the changes will reflect in the Listbox automatically.

ObservableCollection also implements INotifyPropertyChanged so any property updates will also be updated in the ListBox.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top