ZedGraph 对象空引用异常
本文关键字:异常 引用 对象 ZedGraph | 更新日期: 2023-09-27 18:21:21
我在 WinForm 的构造函数中使用ZedGraphControl
绘制图形时遇到问题,我像这样初始化图形:
ZedGraphControl Graph = new ZedGraphControl();
Graph.Dock = DockStyle.Fill;
GroupBoxGraph.Controls.Add(Graph);
GraphPane pane = Graph.GraphPane;
/*Initial pane settings*/
pane.XAxis.Type = AxisType.Date;
pane.XAxis.Scale.Format = "HH:mm:ss";
pane.XAxis.Scale.Min = (XDate)(DateTime.Now);
//Shows 30 seconds interval.
pane.XAxis.Scale.Max = (XDate)(DateTime.Now.AddSeconds(30));
pane.XAxis.Scale.MinorUnit = DateUnit.Second;
pane.XAxis.Scale.MajorUnit = DateUnit.Minute;
pane.XAxis.MajorTic.IsBetweenLabels = true;
pane.XAxis.MinorTic.Size = 5;
RollingPointPairList list = new RollingPointPairList(1200);
LineItem curve = pane.AddCurve("Hmi Mode", list, Color.Blue, SymbolType.None);
Graph.AxisChange();
tickStart = Environment.TickCount;
只是为了测试,我想在单击按钮时绘制一个新点。所以在按钮单击我想执行以下代码:
private void button1_Click(object sender, EventArgs e)
{
if (Graph != null) {
// Make sure that the curvelist has at least one curve
if (Graph.GraphPane.CurveList.Count <= 0)
return;
// Get the first CurveItem in the graph
LineItem curve = Graph.GraphPane.CurveList[0] as LineItem;
if (curve == null)
return;
// Get the PointPairList
IPointListEdit list = curve.Points as IPointListEdit;
// If this is null, it means the reference at curve.Points does not
// support IPointListEdit, so we won't be able to modify it
if (list == null)
return;
// Time is measured in seconds
double time = (Environment.TickCount - tickStart) / 1000.0;
// 3 seconds per cycle
list.Add(time, Math.Sin(2.0 * Math.PI * time / 3.0));
// Keep the X scale at a rolling 30 second interval, with one
// major step between the max X value and the end of the axis
Scale xScale = Graph.GraphPane.XAxis.Scale;
if (time > xScale.Max - xScale.MajorStep) {
xScale.Max = time + xScale.MajorStep;
xScale.Min = xScale.Max - 30.0;
}
// Make sure the Y axis is rescaled to accommodate actual data
Graph.AxisChange();
// Force a redraw
Graph.Invalidate();
}
}
但是我的图形对象总是空的!我甚至创建了一个属性并在 setter 中放置了一个断点。从不调用资源库,但对象仍为 null。(在我发布的第一行代码之后,Graph
对象不为空。
知道这是怎么发生的吗?谢谢
您的第一个代码块看起来像是在创建一个名为 Graph
的局部变量,但您的第二个代码块button1_Click
看起来像是在尝试使用名为 Graph
的类字段(或属性(。这是两个不同的实体。因此,您的初始化代码可能永远不会将ZedGraphControl
实例分配给Graph
字段,因此它始终null
。
尝试更改您的第一个代码以删除局部变量声明并改为引用该字段。 也就是说,将第一行更改为:
Graph = new ZedGraphControl();