【问题标题】:Operation is not valid due to the current state of the object. When I delete a Button由于对象的当前状态,操作无效。当我删除一个按钮
【发布时间】:2018-03-18 04:01:10
【问题描述】:

随着我开始学习 XAML 和 C#,我正在制作一个 POS 项目作为对自己的挑战。

当我尝试删除按钮时会出现问题。我收到一个异常说 System.InvalidOperationException: 'Operation is not valid due to the current state of the object.'

我在网上搜索了很多,但没有找到任何有用的东西。

 private void CB_del_Click(object sender, RoutedEventArgs e)
    {
        foreach (Window window in Application.Current.Windows)
        {
            if (window.GetType() == typeof(MainWindow))
            {
                try
                {
                    foreach (Button btn_tst in ((window as MainWindow).SP_plates).Children)
                    {

                        if ((btn_tst as Button).Name == "btn_cheeseburger")

                            if (I_cheese == 1)
                            {
                                (window as MainWindow).SP_plates.Children.Remove((Button)sender);

                            }

                        if (I_cheese != 0)
                        {
                            I_cheese = I_cheese - 1;
                            String count = I_cheese.ToString();
                            String str;
                            str = "CheeseBurger  $7.5  : " + " " + count;
                            Char[] TrimChar = { '(', ')', ',', '.', '.' };
                            String Name = str.Trim(TrimChar);
                            String Name2 = Name.TrimEnd(TrimChar);
                            btn_tst.Content = Name2;
                        }

                    }


                }
                catch (Exception)
                {
                    MessageBox.Show("test");
                    throw new InvalidOperationException();
                }

            }
        }
    }

【问题讨论】:

  • 异常发生在哪一行?
  • 我无法确定我得到的只是错误
  • 它只给了我一个例外而没有告诉我它发生在哪里
  • 那我该如何解决呢?
  • 请注意,您对window as MainWindow 的使用看起来很奇怪。不是检查window.GetType() == typeof(MainWindow),而是赋值var mainWindow = window as MainWindow,然后检查是否mainWindow != null,以后只使用mainWindow。

标签: c# wpf xaml


【解决方案1】:

您可以考虑删除按钮,而不是删除按钮

  • 将其可见性设置为隐藏
  • 将其启用设置为 false 并将其文本设置为“缺货”
  • 查看 Converters 和 Binding 并将按钮的可见性设置为转换器,该转换器将汉堡的“计数”转换为可见性值,以便在计数 == 0 时自动隐藏。

或者类似的东西。

【讨论】:

  • 您为我节省了数小时的研究和挫败感。我希望我早点在这里问过
  • 我一定会看看转换器和绑定,非常感谢您的提示。
猜你喜欢
  • 2010-10-18
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多