0

这是我第一次使用 stackoverflow,所以我对我做错的任何事情感到抱歉。

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

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

4

1 回答 1

0

您可以使用该Control.Parent属性来访问包含控件。在这里,我们连接了 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);
    }
}
于 2012-07-13T22:28:35.093 回答