为什么每次我调用它时都会执行两次该方法?
问题描述:
我有以下方法两次它被称为每次执行:为什么每次我调用它时都会执行两次该方法?
public static void ChangeToRepository(RepositoryTextBox textBox, int repositoryNumber)
{
MessageBox.Show("you");
int indexOfLastRepository = (textBox.RepositoryCollection.Count - 1);
if (repositoryNumber > indexOfLastRepository)
{
AddTextRepositoriesThrough(textBox, repositoryNumber, indexOfLastRepository);
}
textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText = textBox.Text;
textBox.PreviousRepositoryNumber = textBox.CurrentRepositoryNumber;
textBox.CurrentRepositoryNumber = repositoryNumber;
textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;
}
第一次的方法执行,它执行的所有代码,除了它的最后一行:
textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;
第二次,它执行所有的代码。这是怎么回事?
答
当您在文本框中指定CurrentRepositoryNumber
时,可能会触发一个事件处理程序,该处理程序会再次回调该函数。这可能是因为属性名称暗示它控制着当前的存储库,然后该方法负责以某种方式显示。
您可能希望临时除名,分配给该属性,然后重新登记该事件处理程序。或者,也许你需要更多的重新设计,以获得职责明确的 - 往往与GUI框架是很难做的,最简单的办法是只退市,分配,重新登记,以这种模式:
textBox.TextChange -= YourHandler;
textBox.Text = newValue;
textBox.TextChange += YourHandler;
+0
我忘记了创建调用ChangeToRepository方法的OnCurrentRepositoryNumberChanged事件。谢谢。 – Justin 2010-04-15 21:04:22
你能展示更多的代码吗?代码中调用的函数在哪里?也许这段代码被调用两次(event?)? – Sascha 2010-04-15 20:48:11
请显示所有从哪里来的地方。 – 2010-04-15 20:48:58
您是否从事件处理函数调用ChangeToRepository?哪一个 ?显示该代码。 – nos 2010-04-15 20:49:26