[英]How do I use a specific class based on the selected tab in a TabControl?
I have a TabControl with the TabPages named foo
, bar
, abd baz
in the Main form.我有一个 TabControl,其 TabPages 在主窗体中名为
foo
、 bar
、 abd baz
。 When a user changes to the bar
tab I want it to use the code in the bar.cs
class, when a user changes to the baz
tab, I want to run the code in the baz.cs
class, etc. Kind of like an "all-in-one" form in the sense that it has multiple different functionalities but I don't want all the code to be in one single class.当用户更改为
bar
选项卡时,我希望它使用bar.cs
class 中的代码,当用户更改为baz
选项卡时,我想运行baz.cs
class 等中的代码。有点像“一体式”形式在某种意义上说它具有多种不同的功能,但我不希望所有代码都在一个 class 中。
How can I achieve this?我怎样才能做到这一点? Is this even the proper way of doing something like this?
这甚至是做这种事情的正确方法吗?
If you're just looking to break up the code so you don't have one enormous Form then a standard approach is to break the contents of each tab page out into a custom User Control (a reusable composite control).如果您只是想分解代码以便没有一个巨大的表单,那么标准方法是将每个标签页的内容分解为自定义用户控件(可重用的复合控件)。
Maybe I'm not understanding the question, but it seems rather straightforward to me that you can subscribe to the SelectedIndexChanged
event, instantiate the appropriate class, and run the code.也许我不理解这个问题,但对我来说,您可以订阅
SelectedIndexChanged
事件、实例化适当的 class 并运行代码,这似乎相当简单。
private void OnSelectedIndexChanged(object sender, EventArgs e)
{
switch (myTabControl.SelectedTab.Name)
{
case "foo":
{
var o = new foo();
o.RunCode();
break;
}
case "bar":
{
var o = new bar();
o.RunCode();
break;
}
case "baz":
{
var o = new baz();
o.RunCode();
break;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.