我在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();
}
}
但是我的Graph Object总是为null!我甚至创建了一个属性并在setter中放置了一个断点。永远不会调用setter,但对象仍为null。 (在我发布的第一行代码后,Graph
对象不为空。
知道如何发生这种情况吗?谢谢
答案 0 :(得分:0)
您的第一个代码块看起来像是在创建一个名为Graph
的本地变量,但您的第二个代码块button1_Click
看起来像是在尝试使用名为Graph
的类字段(或属性)。这是两个不同的实体。因此,初始化代码可能永远不会将ZedGraphControl
的实例分配给Graph
字段,因此它总是null
。
尝试更改第一个代码以删除局部变量声明并改为引用该字段。也就是说,将第一行更改为:
Graph = new ZedGraphControl();