WP7通过消息框从listBox中删除项目

时间:2013-04-04 13:02:56

标签: windows-phone-7 listboxitems

需要一些帮助,当我点击tap_event我得到一个消息框删除或取消哪个有效并且价格取消了总数但它没有更新购物车之后,它崩溃了“ListBoxCart.Items.Remove (curr),提前谢谢!

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


    }

2 个答案:

答案 0 :(得分:0)

为ListBox设置ItemsSource属性时,它会生成一个read-only集合并显示它们。你要做的是访问这个只读集合并修改它,但因为它是只读的,你不能这样做。

相反,您可以让您的收藏集实现INotifyCollectionChanged界面,并在用户删除该项目时引发收藏更改事件,或使用ObservableCollection来存储您的项目。 ObservableCollection为您实现了INotifyCollectionChanged界面,因此您可以ObservableCollection remove items,并且更改会自动反映在列表框中。

ObservableCollection还实现了INotifyPropertyChanged,因此任何属性更新也将在ListBox中更新。

答案 1 :(得分:0)

我写了一篇文章(抱歉用法语,但你可以阅读XAML):http://www.peug.net/2012/05/17/contextmenu-dans-listbox-datatemplate/

并在代码隐藏中:示例:

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