开发者

Why is this method executing twice each time I call it?

I have the following method that is executing twice every time it is called:

public static void ChangeToRepository(RepositoryTextBox textBox, int repositoryNumber)
    {
        MessageBox.Show("you");
        int indexOfLastRepository = (textBox.RepositoryCollection.Count - 1);
        if (repositoryNumber > index开发者_如何学COfLastRepository)
        {
            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;
    }

The first time that the method executes, it executes all of the code except for its last line:

textBox.Text = textBox.RepositoryCollection[textBox.CurrentRepositoryNumber].CurrentText;

The second time, it executes all of the code. What's up?


When you assign to CurrentRepositoryNumber on the text box, it probably triggers an event handler that calls back to this function again. This seems likely because the property name suggests that it controls the current repository, which this method then is responsible for displaying somehow.

You might want to temporary delist, assign to the property and then re-enlist that event handler. Or maybe you need more of a redesign to get the responsibilities clear - often with GUI frameworks that is hard to do, and the simplest option is to just delist, assign, re-enlist, with this kind of pattern:

textBox.TextChange -= YourHandler;
textBox.Text = newValue;
textBox.TextChange += YourHandler;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜