Why is the tab page body not updating with a .NET tab control?

狂风中的少年 提交于 2021-01-27 09:39:01

问题


I am having a strange problem with the .NET TabControl in C# (Visual Studio 2010). Start a Windows Forms Application. Add a tab control and a button. Add two different labels to the two tab pages so you can differentiate them. The purpose of the button is just to act as a next button; subscribe to the its Click event with the code:

tabControl1.SelectTab(1);

Let's assume the user entered something wrong on the first tab, so when they try to go to the second tab we want to send them back, so subscribe to the tab control's SelectedIndexChanged event with the code:

if(tabControl1.SelectedIndex == 1)
{
    tabControl1.SelectTab(0);
}

Now run the program and click the button. You will notice that as judged by the highlighted tab at the top, the first tab page is the one that appears to be selected, as you'd expect. However, as judged by the tab page that actually appears in the body of the tab control, it's still the second tab page that shows up! Calls to various controls' Focus(), Update(), and Refresh() functions don't seem to help. What is going on here?


回答1:


I repro. This is a generic problem with event handlers, you can confuse the stuffing out the native Windows control by jerking the floor mat like that. TreeView is another control that's very prone to this kind of trouble.

There's an elegant and general solution for a problem like this, you can use Control.BeginInvoke() to delay the command. It will execute later after the native control is done with the event generation and all side-effects have been completed. Which solves this problem as well, like this:

    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {
        if (tabControl1.SelectedIndex == 1) {
            this.BeginInvoke(new Action(() => tabControl1.SelectTab(0)));
        }
    }


来源:https://stackoverflow.com/questions/11059859/why-is-the-tab-page-body-not-updating-with-a-net-tab-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!