C#WinForms /如何访问包含自定义控件的表单的控件?

时间:2011-03-12 00:23:51

标签: .net winforms

假设我在MainForm中添加了一个CustomListView控件。

// CustomListView.cs

class CustomListView : ListView
{
    public CustomListView()
    {
        ItemActivate += new EventHandler(ItemActivateEvent);
    }

    private void ItemActivateEvent(object sender, EventArgs e)
    {
        // update label in the parent form
    }
}

如何从那里访问MainForm的其他控件?

1 个答案:

答案 0 :(得分:1)

从MainForm中创建EventHandler会更容易。通过这种方式,您可以使用MainForm轻松控制CustomListView控件以及MainForm控件。

这样的事情:

MAINFORM.CS:

private void button1_Click(object sender, EventArgs e)
{
    // Creates and displays the custom control on your MainForm and 
    //     attaches an event to it.

    CustomListViewControl lv = new CustomListViewControl();
    this.Controls.Add(lv);

    lv.ItemActivate += new EventHandler(ItemActivateEvent);
}

void ItemActivate(object sender, EventArgs e)
{
    // Do some stuff with MainForm or its child controls in here.

    this.Text = "I am uber awesome";
    this.Hide();



}