.net C#WinForms/如何访问包含自定义控件的窗体的控件?
假设我在MainForm中添加了一个CustomListView控件.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
// 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管理自己的事件,这不是更好的设计吗?