【发布时间】: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。