将图表添加为单独类中的控件. 图表未绘制



我正在添加一个图表作为在单独类中创建的控件。图表的背景是绘画,但图表本身不是绘画。有人可以指出我的错误在哪里吗?我尝试过BringToFront,Anchoring,Dock.Fill,Invalidate之类的东西。

using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
ChartControl MyChart;
public Form1()
{
InitializeComponent();
MyChart = new ChartControl();
this.Controls.Add(MyChart);
MyChart.chart1.Series[0].Points.AddXY(1.4, 1.3);
MyChart.chart1.Series[0].Points.AddXY(1.7, 1.9);
}
}
}

图表类

using System.Windows.Forms.DataVisualization.Charting;
namespace WindowsFormsApp2
{
public class ChartControl : Chart
{
public Chart chart1;
public ChartControl()
{
ChartArea chartArea1 = new ChartArea();
Legend legend1 = new Legend();
Series series1 = new Series();
chart1 = new Chart();
((System.ComponentModel.ISupportInitialize)chart1).BeginInit();
SuspendLayout();
chartArea1.Name = "ChartArea1";
chart1.ChartAreas.Add(chartArea1);
legend1.Name = "Legend1";
chart1.Legends.Add(legend1);
chart1.Location = new System.Drawing.Point(0, 0);
chart1.Name = "chart1";
series1.ChartArea = "ChartArea1";
series1.Legend = "Legend1";
series1.Name = "Series1";
chart1.Series.Add(series1);
chart1.Size = new System.Drawing.Size(300, 300);
chart1.TabIndex = 0;
chart1.Text = "chart1";
((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
ResumeLayout(false);
}
}
}

您要添加MyChart的表单没有可绘制的内容,因为您将所有数据添加到MyChart.chart1,这是您在ChartControl类中创建的附加字段。

您正在chart1中操作所有"图表"数据,但是用于绘制内容的所有WinForm代码都在您在ChartControl中扩展的Chart类中,该类不知道chart1是什么(甚至不存在)。

我的猜测是你正在创建这种类型的"包装器"类来将特定样式应用于图表。如果是这种情况,您需要确保直接操作从Chart继承ChartControl属性,而不是创建自定义属性或字段(除非您打算覆盖 paint 方法以使用它们)。

示例构造函数:

public ChartControl()
{
ChartArea chartArea1 = new ChartArea();
Legend legend1 = new Legend();
Series series1 = new Series();
chartArea1.Name = "ChartArea1";
this.ChartAreas.Add(chartArea1);
this.Name = "chart1";
series1.ChartArea = "ChartArea1";
series1.Legend = "Legend1";
series1.Name = "Series1";
this.Series.Add(series1);
this.Text = "chart1";
}

正如@TaW提到的 - 我同意 - 并不是一个很好的设计方法,但仍然应该有效(尽管我还没有测试过这段代码)。

最新更新