如何通过usercontrol访问我的tabpage名称? C#

时间:2012-07-13 19:37:41

标签: c# tabs

这是我第一次使用stackoverflow,所以我很抱歉我做错了。

我在Microsoft Visual C#2010 Express Edition中制作选项卡式网页浏览器时出现问题,问题是我希望将标签页命名为网页名称,但我为每个标签使用了一个usercontrol实例,因为tabcontrol不是静态的我不能从usercontrol类更改名称。我该怎么做才能解决这个问题?

任何提示都会有所帮助。 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用Control.Parent属性访问包含的Control。在这里,我们连接TabPage,以便更改UserControl的Text属性自动更新父TabPage。您可以在创建新的TabPage和UserControl时执行此连接。

using System;
using System.Windows.Forms;

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Form form = new Form
        {
            Controls =
            {
                new TabControl
                {
                    Dock = DockStyle.Fill,
                    Name = "TabControl1",
                    TabPages =
                    {
                        new TabPage { Name = "Page1", Text = "Page 1", Controls = { new UserControl { } } },
                        new TabPage { Name = "Page2", Text = "Page 2", Controls = { new UserControl { } } },
                    },
                },
            },
        };

        // Hookup the TabPage so that when it's UserControl's Text property changes, its own Text property is changed to match
        // Now you can simply alter the UserControl's Text property to cause the TabPage to change
        foreach (TabPage page in ((TabControl)form.Controls["TabControl1"]).TabPages)
            page.Controls[0].TextChanged += (s, e) => { Control c = (Control)s; c.Parent.Text = c.Text; };

        // Demonstrate that when we change the UserControl's Text property, the TabPage changes too
        foreach (TabPage page in ((TabControl)form.Controls["TabControl1"]).TabPages)
            page.Controls[0].Text = "stackoverflow.com";

        Application.Run(form);
    }
}