【问题标题】:WP7 delete item from listBox via message boxWP7 通过消息框从列表框中删除项目
【发布时间】:2013-04-04 13:02:55
【问题描述】:

需要一些帮助,当我单击 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));
        }


    }

【问题讨论】:

  • 错误信息是什么?
  • InvalidOperationException 未处理
  • 抱歉,只读集合不支持操作。
  • 您不能从列表框中删除项目。您需要从提供的项目集合中删除项目。
  • @Fabrice 感谢您的快速回复,我完全采取了错误的方法,我只能添加/删除集合而不是列表框,非常感谢

标签: windows-phone-7 listboxitems


【解决方案1】:

我写了一篇文章(抱歉是法语,但您可以阅读 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();
    }

【讨论】:

    【解决方案2】:

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

    相反,您可以让您的集合实现INotifyCollectionChanged 接口并在用户删除项目时引发集合更改事件,或者使用ObservableCollection 来存储您的项目。 ObservableCollection 为您实现了INotifyCollectionChanged 接口,因此您可以从ObservableCollectionremove items 并且更改将自动反映在列表框中。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 2020-12-07
      • 2010-11-29
      • 1970-01-01
      相关资源
      最近更新 更多