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

时间:2022-09-02 12:35:33

Let's say I got a CustomListView control added into MainForm.

假设我在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
    }
}

How can I access MainForm's other controls from there?

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

1 个解决方案

#1


1  

It would be easier to create the EventHandler from within the MainForm. That way you can very easily control your CustomListView Control and also your MainForm Control from with your MainForm.

从主窗体中创建EventHandler更容易。这样,您就可以很容易地从主窗体中控制CustomListView控件和主窗体控件。

Something like this:

是这样的:

MAINFORM.CS:

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



}

#1


1  

It would be easier to create the EventHandler from within the MainForm. That way you can very easily control your CustomListView Control and also your MainForm Control from with your MainForm.

从主窗体中创建EventHandler更容易。这样,您就可以很容易地从主窗体中控制CustomListView控件和主窗体控件。

Something like this:

是这样的:

MAINFORM.CS:

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



}