动态添加 ChartAreas 到列中的 Chart 并使 Chart 在 winforms 中自动滚动

Dynamically add ChartAreas to Chart in a column and make Chart auto-scrollable in winforms

我需要你的建议。我想在我的图表中添加许多 ChartAreas 并在一列中垂直对齐它们,这将是其父项的 100% 宽度,并且当添加更多聊天区域时该列将变得可滚动。 现在,我使用此代码添加更多图表区域:

private void AddChartArea(int index)
{
    string chartAreaName = index.ToString();
    chart.ChartAreas.Add(chartAreaName);
    chart.Series.Add(new Series());
    chart.Series[index].ChartType = SeriesChartType.Line;
    chart.Series[index].MarkerStyle = MarkerStyle.Diamond;
    chart.Series[index].ChartArea = chartAreaName;

    /* Trying to align chart areas vertically */
    chart.ChartAreas[index].AlignWithChartArea = chart.ChartAreas[index - 1].Name;
    chart.ChartAreas[index].AlignmentStyle = AreaAlignmentStyles.AxesView;
    chart.ChartAreas[index].AlignmentOrientation = AreaAlignmentOrientations.Vertical;
}

但是当图表区域数量 > 3 时,我的图表区域仍然是这样的:

虽然我希望它是这样的,但右侧有一个垂直滚动条:

因此,正如 TaW 所指出的,我的问题类似于 this one。但我做了一些改进以自动调整整体图表高度。

所以我的图表被放置在面板中,面板的自动滚动为真。 然后,每次我创建一个新的 ChartArea 时调用这个方法:

private void DrawNewChartArea(int index)
{
    int chartAreaMinHeight = 200;
    chart.Dock = DockStyle.Top;

    float width = 99;
    float height = 100 / chart.ChartAreas.Count;
    float x = 0;
    float y = height * index;

    if (chartAreaMinHeight * (index + 1) > chart.Height)
    {
        chart.Height = chartAreaMinHeight * (index + 1);
        // realign height of all the chart areas if we are changing chart height
        for (int i = 0; i < chart.ChartAreas.Count; i++)
        {
            float caY = height * i;
            chart.ChartAreas[i].Position.Height = height;
            chart.ChartAreas[i].Position.Y = caY;
        }
    }

    chart.ChartAreas[index].Position = new ElementPosition(x, y, width, height);
}