将图表控件复制到新表格

时间:2013-07-29 07:23:12

标签: copy controls microsoft-chart-controls

有没有办法将图表控件复制到新表单? 我有一个带有图表控件的Windows窗体,但不允许该窗体可调整大小。出于这个原因,我有一个按钮" Zoom"以可调整大小的新形式打开图表。我在"原创"中设置了很多图表属性。图表(轴颜色,轴间隔等),并希望重用此属性。我试图用图表作为参数调用新表单的构造函数,但是没有用。

public ZoomChartSeriesForm(Chart myChart)

我的主要问题是,当我复制图表时,我允许在图表内部进行缩放并崩溃。

这是我"原始图表的代码" (实施例):

   
        System.Drawing.Color color = System.Drawing.Color.Red;
        //plot new doublelist
        var series = new Series
        {
            Name = "Series2",
            Color = color,
            ChartType = SeriesChartType.Line,
            ChartArea = "ChartArea1",
            IsXValueIndexed = true,
        };

        this.chart1.Series.Add(series);

        List<double> doubleList = new List<double>();
        doubleList.Add(1.0);
        doubleList.Add(5.0);
        doubleList.Add(3.0);
        doubleList.Add(1.0);
        doubleList.Add(4.0);

        series.Points.DataBindY(doubleList);

        var chartArea = chart1.ChartAreas["ChartArea1"];
        LabelStyle ls = new LabelStyle();
        ls.ForeColor = color;
        Axis a = chartArea.AxisY;
        a.TitleForeColor = color; //color of axis title
        a.MajorTickMark.LineColor = color; //color of ticks                  
        a.LabelStyle = ls; //color of tick labels

        chartArea.Visible = true;
        chartArea.AxisY.Title = "TEST";
        chartArea.RecalculateAxesScale();
        chartArea.AxisX.Minimum = 1;
        chartArea.AxisX.Maximum = doubleList.Count;

        // Set automatic scrolling 
        chartArea.CursorX.AutoScroll = true;
        chartArea.CursorY.AutoScroll = true;
        // Allow user to select area for zooming
        chartArea.CursorX.IsUserEnabled = true;
        chartArea.CursorX.IsUserSelectionEnabled = true;
        chartArea.CursorY.IsUserEnabled = true;
        chartArea.CursorY.IsUserSelectionEnabled = true;
        // Set automatic zooming
        chartArea.AxisX.ScaleView.Zoomable = true;
        chartArea.AxisY.ScaleView.Zoomable = true;
        chartArea.AxisX.ScrollBar.IsPositionedInside = true;
        chartArea.AxisY.ScrollBar.IsPositionedInside = true;
        //reset zoom
        chartArea.AxisX.ScaleView.ZoomReset();
        chartArea.AxisY.ScaleView.ZoomReset();

        chart1.Invalidate();

1 个答案:

答案 0 :(得分:1)

像深度复制对象一样复制?

我最近遇到了这个问题。遗憾的是,MS Chart没有方法来克隆他们的图表对象,并且他们的类没有标记为可序列化,因此您无法使用建议的方法here

如果你想以正确的方式做到这一点,你必须引入第三方控件,例如Copyable或自己处理反射,但这并不容易。

我发现一个非常好的解决方法是使用MS Chart控件中的内置序列化。我们的想法是使用memorystream序列化图表,创建图表的新实例并反序列化图表。

private Chart CloneChart(Chart chart)
{
    MemoryStream stream = new MemoryStream();
    Chart clonedChart = chart;
    clonedChart.Serializer.Save(stream);
    clonedChart = new Chart();
    clonedChart.Serializer.Load(stream);
    return clonedChart;
}

这不是一个有效的解决方案,但如果性能不是您的首选,那就像魅力一样。

相关问题