0

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

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();
4

1 回答 1

1

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

我最近自己遇到了这个确切的问题。不幸的是,MS Chart 没有方法来克隆他们的图表对象,并且他们的类没有被标记为可序列化,所以你不能使用这里建议的方法。

如果您想以正确的方式执行此操作,则必须引入第三方控件(例如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;
}

不完全是一个有效的解决方案,但如果性能不是你的首要任务,这就像一个魅力。

于 2013-07-29T07:31:00.510 回答