我正在编写一个带有两个按钮的简单用户控件:保存和取消。我认为它认为没有订阅者,因为它总是在我在代码中指示的位置为null。请帮忙。
以下是用户控件的代码:
public partial class SaveCancelButtons : UserControl
{
public delegate void SaveClickedHandler();
public delegate void CancelClickedHandler();
public SaveCancelButtons()
{
InitializeComponent();
}
public event SaveClickedHandler SaveClicked;
public event CancelClickedHandler CancelClicked;
protected virtual void OnSaveClicked()
{
if (SaveClicked != null) <<<<----- ALWAYS NULL
{
SaveClicked(); // Notify Subscribers
}
}
protected virtual void OnCancelClicked()
{
if (CancelClicked != null) <<<<----- ALWAYS NULL
{
CancelClicked(); // Notify Subscribers
}
}
private void btnSave_Click(object sender, System.EventArgs e)
{
OnSaveClicked();
}
public void btnCancel_Click(object sender, EventArgs e)
{
OnCancelClicked();
}
}
以下是我如何称呼它:
public partial class TestForm : Form
{
public TestForm()
{
// declare and subscribe to the user control
SaveCancelButtons scb = new SaveCancelButtons();
scb.SaveClicked += UC_SaveClicked;
scb.CancelClicked += UC_CancelClicked;
this.Controls.Add(scb);
InitializeComponent();
}
private void UC_SaveClicked()
{
MessageBox.Show("Save!");
}
private void UC_CancelClicked()
{
MessageBox.Show("Cancel");
}
}
答案 0 :(得分:1)
您正在尝试在此处混合代理和事件。如果您想要的是在单击用户控件按钮时要调用的表单方法,请在用户控件中声明事件并在表单中注册回调函数。我对您的代码进行了更改。此代码将显示用户控件中单击按钮的对话框
public partial class SaveCancelButtons : UserControl
{
public delegate void SaveClickedHandler();
public delegate void CancelClickedHandler();
public SaveCancelButtons()
{
InitializeComponent();
}
public event EventHandler SaveClicked;
public event EventHandler CancelClicked;
protected virtual void OnSaveClicked()
{
EventHandler handler = SaveClicked;
if (SaveClicked != null) //
{
handler(this,new EventArgs()); // Notify Subscribers
}
}
protected virtual void OnCancelClicked()
{
EventHandler handler = CancelClicked;
if (CancelClicked != null) // <<<<
{
handler(this,new EventArgs()); // Notify Subscribers
}
}
private void btnSave_Click(object sender, EventArgs e)
{
OnSaveClicked();
}
private void btnCancel_Click(object sender, EventArgs e)
{
OnCancelClicked();
}
}
您的表单更改
public partial class TestForm : Form
{
public TestForm()
{
// declare and subscribe to the user control
SaveCancelButtons scb = new SaveCancelButtons();
scb.SaveClicked += Scb_SaveClicked; ;
scb.CancelClicked += Scb_CancelClicked; ;
this.Controls.Add(scb);
InitializeComponent();
}
private void Scb_CancelClicked(object sender, EventArgs e)
{
MessageBox.Show("Cancel");
}
private void Scb_SaveClicked(object sender, EventArgs e)
{
MessageBox.Show("Save!");
}
}