问题描述
我有一个表格和一个用户控件。在我的用户我有一个按钮,我想打电话给从形式的方法。在C#谁能帮助?
I have a Form and a UserControl. In my UserControl I have a button, and I would like to call a method from the Form. Can anyone help in C#?
推荐答案
您需要创建的用户控件的按钮事件的事件处理程序,并从火了。实际按钮的Click事件
You need to create an event handler for the button-event of the usercontrol and fire it from the click event of the actual button.
class MyControl : UserControl
{
public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
public event ButtonClickedEventHandler OnUserControlButtonClicked;
}
现在你要听实际按钮的情况下, >
Now you need to listen to the event of the actual button:
class MyControl : UserControl
{
// See above
public MyControl()
{
_myButton.Clicked += new EventHandler(OnButtonClicked);
}
private void OnButtonClicked(object sender, EventArgs e)
{
// Delegate the event to the caller
if (OnUserControlButtonClicked != null)
OnUserControlButtonClicked(this, e);
}
}
从主窗体(老板),你现在可以听事件:
From the main form (owner) you can now listen to the event:
public FancyForm : Form
{
public FancyForm()
{
_myUserControl.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
}
private void OnUCButtonClicked(object sender, EventArgs e)
{
// Handle event from here
MessageBox.Show("Horray!");
}
}
更新:这两种实现方式甚至可以安全使用Lambda表达式和默认EventHandler委托定义的几行代码
Update: Both implementations can even safe a few lines of code by using Lambdas and default EventHandler delegate definitions.
class MyControl : UserControl
{
public event EventHandler OnUserControlButtonClicked;
// Use this, if you want to use a different EventArgs implementation:
// public event EventHandler<CustomEventArgs> OnUserControlButtonClicked;
public MyControl()
{
_myButton.Clicked += (s, e) =>
{
if (OnUserControlButtonClicked != null)
OnUserControlButtonClicked(this, e);
}
}
}
public FancyForm : Form
{
public FancyForm()
{
_myUserControl.OnUserControlButtonClicked += (s, e) => MessageBox.Show("Horray!");
}
}
更新2 :安全更行与C#6功率:
Update 2: Safe even more lines with the power of C# 6:
class MyControl : UserControl
{
public event EventHandler OnUserControlButtonClicked;
public MyControl()
{
_myButton.Clicked += (s, e) => this.OnUserControlButtonClicked?.Invoke(this, e);
}
}
这篇关于C#用户控件按钮单击事件处理程序来调用主窗体的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!