简体   繁体   English

如何根据 TabControl 中选定的选项卡使用特定的 class?

[英]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 在主窗体中名为foobar 、 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).如果您只是想分解代码以便没有一个巨大的表单,那么标准方法是将每个标签页的内容分解为自定义用户控件(可重用的复合控件)。

  1. In Visual Studio, add a new item to your project and select "User Control".在 Visual Studio 中,将新项目添加到您的项目和 select“用户控件”。
  2. Use the designer to add whatever controls/logic/events/properties you want.使用设计器添加您想要的任何控件/逻辑/事件/属性。
  3. Build your project.构建您的项目。 After the build is complete, you should see your new UserControl in the VS Toolbox, probably near the top.构建完成后,您应该会在 VS 工具箱中看到新的 UserControl,可能靠近顶部。
  4. Drag your control onto the desired TabPage in your Form.将您的控件拖到表单中所需的 TabPage 上。 Set its Dock property to Full so it fills the tab control.将其 Dock 属性设置为 Full,以便填充选项卡控件。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM