委托事件用法
ExampleSpectrum3D.cs
1、用户控件引用了另外的用户控件ViewPointEditor.cs 、RowDataGenerator.cs,在单击start事件发生时,程序运行情况是
- 在RowDataGenerator.cs中运行单击事件函数
private void buttonStart_Click(object sender, EventArgs e)
{
Start();
}
public void Start()
{
_peak1X = (double) _rowLength / 8.0;
_peak2X = (double) _rowLength / 2.0;
timer1.Interval = (int) numericUpDownInterval.Value;
timer1.Start();
m_bRunning = true;
if (Started != null)
Started(this, null);
}
RowDataGenerator.cs中定义事件 开始 结束
//Start/stop events
public event EventHandler Started;
public event EventHandler Stopped;
控件中公开的事件 Started,可以在另一个调用此控件的窗体中注册一个函数
public ExampleSpectrum3D()
{
InitializeComponent();
CreateChart();
viewPointEditor1.Chart = _chart;
rowDataGenerator.IntervalMs = 25;
rowDataGenerator.NewDataGenerated += rowDataGenerator_NewDataGenerated;
rowDataGenerator.Started += rowDataGenerator1_Started;
rowDataGenerator.Stopped += rowDataGenerator1_Stopped;
}
在控件ExampleSpectrum3D中注册到控件RowDataGenerator.Start事件的函数
private void rowDataGenerator1_Started(object sender, EventArgs e)
{
///
}
private void rowDataGenerator_NewDataGenerated(ref double[] data)
{
//Disable rendering, strongly recommended before updating chart properties
_chart.BeginUpdate();
_currentZ += _stepZ;
if (radioButtonSurface.Checked || radioButtonSurfaceAndArea.Checked)
{
SetNewDataToSurface(data);
}
if (radioButtonArea.Checked)
{
SetNewDataToWaterfall(data);
}
if (radioButtonSurfaceAndArea.Checked)
{
//Set the data also to front strip
SetNewDataToFrontWaterfall(data);
}
//Allow chart rendering
_chart.EndUpdate();
}
总结:
可以在控件2的按钮事件中配置相关参数、计时器,再使用一个委托事件(不包含事件数据),
然后在控件1的初始化中把函数注册到控件2的事件中,
就会达到:在控件2中单击,控件2中完成一系列的操作后,再调用委托事件,执行控件1中的注册到事件上的对应函数
有参数的委托事件
public delegate void NewDataGeneratedHandler(ref double[] data);
public event NewDataGeneratedHandler NewDataGenerated;
定时器tick事件中,调用 public double[] GenerateData()函数
函数中调用委托 if (NewDataGenerated != null)
NewDataGenerated(ref aNewData);
并把新数据传递到委托事件的参数中
由于已经将委托事件注册到相应的函数
此时控件 ExampleSpectrum3D 中的刷新数据函数就被调用
private void rowDataGenerator_NewDataGenerated(ref double[] data)