问题描述
我正在使用TabControl并将TabPages附加到TabControl,但是在使其中一个TabPages响应事件时遇到问题.这使我认为我缺少有关这些类之间的关系的信息,因此希望能提供一些帮助.我想向TabControl添加多个TabPage对象,对于其中一个(添加的第一个对象),我想向它发送一个事件以使其执行某些操作.
I am working with a TabControl and attaching TabPages to the TabControl, but am having a problem making one of the TabPages respond to an event. It makes me think that I am missing something about the relationship between these classes, so would appreciate some help. I want to add a number of TabPage objects to TabControl, and for one of them (the first one added), I want to send it an event to make it do something.
这是基本代码:
/* tabControl is a TabControl object, and
tabNames is a string array */
bool first = true;
foreach (string tabName in tabNames)
{
TabPage tabPage = CreateTabPage(tabName);
tabControl.Controls.Add(tabPage);
if (first)
{
methodTabPage.Select();
first = false;
}
}
private TabPage CreateTabPage(String name)
{
TabPage tabPage = new TabPage(name);
tabPage.Enter += new EventHandler(MethodTab_Entered);
return tabPage;
}
private void MethodTab_Entered(object sender, EventArgs e)
{
DoSomething();
}
据我所知,运行此代码时,从未调用过DoSomething().我已经尝试了诸如Click事件之类的各种方法,但是无法使它按预期工作.我想念什么?
When I run this code, as far as I can tell, DoSomething() never gets called. I have tried various things such as the Click event, and so on, but cannot get this to work as expected. What am I missing?
谢谢马丁
推荐答案
这对我来说很好:
public partial class TabPageForm : Form
{
private List<string> tabNames;
public TabPageForm()
{
InitializeComponent();
tabNames = new List<string>();
tabNames.Add("NewTab");
}
private void button1_Click(object sender, EventArgs e)
{
bool first = true;
foreach (string tabName in tabNames)
{
TabPage tabPage = CreateTabPage(tabName);
methodTabPage.Controls.Add(tabPage);
if (first)
{
methodTabPage.Select();
first = false;
}
}
}
private TabPage CreateTabPage(String name)
{
TabPage tabPage = new TabPage(name);
tabPage.Enter += new EventHandler(MethodTab_Entered);
return tabPage;
}
private void MethodTab_Entered(object sender, EventArgs e)
{
DoSomething();
}
private void DoSomething()
{
throw new NotImplementedException();
}
}
进入新创建的标签页时,将调用DoSomething.
DoSomething is called when I enter the newly created tab.
当然,first
变量的逻辑可能不符合您的预期,因此,如果您可以弄清它的语义,就可以更新代码段.
Of course, the logic of the first
variable is probably not as you intend it to be, so if you could clarify the semantics of it, I could update my code snippet.
欢呼
这篇关于C#TabControl TabPage传递事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!