我想用C#中的winforms绘制一些东西。我在网上发现了一段代码,让我开始,我已经包含在下面。我试图理解这些winforms是如何工作的,我想知道的一件事是Form1_Load方法中的部分,它说的是
chart = new Graph.Chart();
变量chart
已在类的开头初始化,但我想为什么不将它移到上面的命令之上。但这不起作用,但我不明白为什么。
当我尝试移动它时,它给了我这个错误:“错误1'plotting.Form1'不包含'chart'的定义,也没有扩展方法'chart'接受类型'的第一个参数plotting.Form1'可以找到(你错过了使用指令或汇编引用吗?)“
using System;
using System.Drawing;
using System.Windows.Forms;
using Graph = System.Windows.Forms.DataVisualization.Charting;
namespace plotting
{
public partial class Form1 : Form
{
Graph.Chart chart; //CAN I MOVE THIS TO (***)?
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
const int MaxX = 20;
// Create new Graph
//(***) DOESN*T WORK, IF I MOVE IT HERE
chart = new Graph.Chart();
chart.Location = new System.Drawing.Point(10, 10);
chart.Size = new System.Drawing.Size(700, 700);
// Add a chartarea called "draw", add axes to it and color the area black
chart.ChartAreas.Add("draw");
chart.ChartAreas["draw"].AxisX.Minimum = 0;
chart.ChartAreas["draw"].AxisX.Maximum = MaxX;
chart.ChartAreas["draw"].AxisX.Interval = 1;
chart.ChartAreas["draw"].AxisX.MajorGrid.LineColor = Color.White;
chart.ChartAreas["draw"].AxisX.MajorGrid.LineDashStyle = Graph.ChartDashStyle.Dash;
chart.ChartAreas["draw"].AxisY.Minimum = -0.4;
chart.ChartAreas["draw"].AxisY.Maximum = 1;
chart.ChartAreas["draw"].AxisY.Interval = 0.2;
chart.ChartAreas["draw"].AxisY.MajorGrid.LineColor = Color.White;
chart.ChartAreas["draw"].AxisY.MajorGrid.LineDashStyle = Graph.ChartDashStyle.Dash;
chart.ChartAreas["draw"].BackColor = Color.Black;
// Create a new function series
chart.Series.Add("MyFunc");
// Set the type to line
chart.Series["MyFunc"].ChartType = Graph.SeriesChartType.Line;
// Color the line of the graph light green and give it a thickness of 3
chart.Series["MyFunc"].Color = Color.LightGreen;
chart.Series["MyFunc"].BorderWidth = 3;
//This function cannot include zero, and we walk through it in steps of 0.1 to add coordinates to our series
for (double x = 0.1; x < MaxX; x += 0.1)
{
chart.Series["MyFunc"].Points.AddXY(x, Math.Sin(x) / x);
}
chart.Series["MyFunc"].LegendText = "sin(x) / x";
// Create a new legend called "MyLegend".
chart.Legends.Add("MyLegend");
chart.Legends["MyLegend"].BorderColor = Color.Tomato; // I like tomato juice!
Controls.Add(this.chart);
}
}
}
答案 0 :(得分:1)
原因是在Form1_Load的末尾,您使用
添加图表Controls.Add(this.chart);
此将图表限定为类的成员(MSDN),但您尝试在Form1_Load方法范围内声明它。
如果您想在方法中使用声明,则必须将最后一行更改为
Controls.Add(chart);