Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net C#WinForms/如何访问包含自定义控件的窗体的控件?_.net_Winforms - Fatal编程技术网

.net C#WinForms/如何访问包含自定义控件的窗体的控件?

.net C#WinForms/如何访问包含自定义控件的窗体的控件?,.net,winforms,.net,Winforms,假设我在MainForm中添加了一个CustomListView控件 // CustomListView.cs class CustomListView : ListView { public CustomListView() { ItemActivate += new EventHandler(ItemActivateEvent); } private void ItemActivateEvent(object sender, EventAr

假设我在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的其他控件?

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

// 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.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();



}

您可能需要将访问修饰符设置为Public或Internal,以便表单可以访问CustomListView。我不记得了,您可能不需要。但如果CustomListView管理自己的事件,这不是更好的设计吗?