How to retrieve the selected range in the .Net WinForms Chart Control?

前端 未结 2 623
轮回少年
轮回少年 2021-01-05 13:37

I\'m using the C# built-in Winforms Chart control (System.Windows.Forms.DataVisualization.Charting.Chart) with its built-in ability to let the user select a range. What I\'d

2条回答
  •  温柔的废话
    2021-01-05 14:07

    In addition to redtuna to set cursors in a c# chart:

    It worked for me to use "SelectionRangeChanging" instead of "SelectionRangeChanged" to not get the NaN issue:

    When initializing the Form

    this.chart1.SelectionRangeChanging += chart1_SelectionRangeChanging;
    

    and

            chart1.ChartAreas[0].CursorX.IsUserEnabled = false;         // red cursor at SelectionEnd
            chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
            chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = false;      // zoom into SelectedRange
            chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            chart1.ChartAreas[0].CursorX.Interval = 0.01;               // set "resolution" of CursorX
    

    What is executed if the range is chosen / the cursors are set

    private void chart1_SelectionRangeChanging(object sender, CursorEventArgs e)
        {
            double x1 = x1 = e.NewSelectionStart; // or: chart1.ChartAreas[0].CursorX.SelectionStart;
            double x2 = e.NewSelectionEnd;        // or: x2 = chart1.ChartAreas[0].CursorX.SelectionEnd;
    
            double diffx1x2 = x2 - x1;
        }    
    

    To zoom in & out (x-axis) I just added a button that takes the cursor values. That way zooming by mouseClick (ScaleView.Zoomable = false;) does not interfere my cursor positioning :)

     private void button_ZoomIn(object sender, EventArgs e)
        {
            double x1 = chart1.ChartAreas[0].CursorX.SelectionStart;  // x1 = X1
            double x2 = chart1.ChartAreas[0].CursorX.SelectionEnd;    // x2 = X2
    
            if (x2 > x1)
            {
                // hard setting: chart1.ChartAreas[0].AxisX.Minimum = x1;
                // hard setting: chart1.ChartAreas[0].AxisX.Maximum = x2;
                chart1.ChartAreas[0].AxisX.ScaleView.Zoom(x1,x2); // dynamic approach with scrollbar
            }
            else
            {
                chart1.ChartAreas[0].AxisX.ScaleView.Zoom(x2,x1);
            }
        }
    

    Zoom out

    private void button_ZoomOut(object sender, EventArgs e)
        {
            chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset(0);
        }
    

    Zooming can also be implemented by mouseWheel: how to enable zooming in Microsoft chart control by using Mouse wheel And if you also want right-click action in the chart: How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

提交回复
热议问题