2011-08-30 62 views
2

我在窗体中有一个标签控件,并且用户控件在窗体加载事件中加载到每个标签页上。我想使用标签页中的命令按钮在标签之间切换,这意味着按钮位于不同的用户控件中,而不是表单中。使用其中的按钮在标签页之间切换

tabControl1.SelectedTab = tabPage2; 

因此无法使用。我怎样才能做到这一点?

+0

检查我在回答中提供的更新 – reggie

回答

3
tabControl1.SelectedIndex = index; 
//where index is the index (integer value) of the tabpage you want to select 

UPDATE

检查: How to access properties of a usercontrol in C#

揭露性质为用户控件这样的性质:

public int TabControlIndex 
{ 
get { return tabControl1.index; } 
set { tabControl1.index = value; } 
} 

你可以调用同您form load event像这个:

Usercontrol1.TabControlIndex = index; 
//where index is the index (integer value) of the tabpage you want to select 
+0

我无法从用户控件访问tabControl,因为它位于表单上,而不是用户控件上。用户控件被加载到标签页上,按钮也在这些用户控件上。 – Lihini

+0

请检查更新。我在上面的答案中提供了一个链接。还添加了一段基于链接中提到的解决方案的代码。让我知道这是否有帮助。 – reggie

+0

非常感谢。这确实有帮助。 – Lihini

0

您可以通过构造函数或一些初始化方法传递TabControl的实例(其PageIndex的一起)到您的用户控件作为参数:

MyUserControl userControl = new MyUserControl(tabControl1, pageIndex1); 

MyUserControl userControl2 = new MyUserControl(); 
userControl2.BindToTabControl(tabControl1, pageIndex2); 

在这种情况下,您的用户控件将能够处理用户点击和切换标签。

或者您可以在UserControl中创建事件,当用户单击UserControl的按钮时将触发事件。你的主表单应该订阅这个事件并处理它们。在这种情况下,您主表单的代码将负责切换选项卡。我认为这是一个更好的解决方案。

+0

非常感谢。我也喜欢你的回答。 – Lihini