Winforms 当用户使用DataVisualization.Charting.Chart单击折线图时获取数据点

Winforms 当用户使用DataVisualization.Charting.Chart单击折线图时获取数据点,winforms,charts,indexing,mschart,Winforms,Charts,Indexing,Mschart,我使用的是DataVisualization.Charting.Chart(winform),当用户在MouseDown事件中单击线条图时,我需要获取数据点索引 我知道有一个接受x&y的HitTest函数,但是对于线图,我们只需要验证x,如果我们扫描y(0到图形的高度),它会工作,但是性能太差。一种方法是启用光标 chartArea1.CursorX.IsUserEnabled = true; chartArea1.CursorX.IsUserSelectionEnabled = true; /

我使用的是DataVisualization.Charting.Chart(winform),当用户在MouseDown事件中单击线条图时,我需要获取数据点索引


我知道有一个接受x&y的HitTest函数,但是对于线图,我们只需要验证x,如果我们扫描y(0到图形的高度),它会工作,但是性能太差。

一种方法是启用光标

chartArea1.CursorX.IsUserEnabled = true;
chartArea1.CursorX.IsUserSelectionEnabled = true;
// set selection color to transparent so that range selection is not drawn
chartArea1.CursorX.SelectionColor = System.Drawing.Color.Transparent;
并处理CursorPositionChanged事件

private void chart1_CursorPositionChanged(object sender, CursorEventArgs e)
{
   // find a point (this series only has Y values, so using position as index works
   // for a series with actual X values, you'd need to Find the closest point
   DataPoint pt = chart1.Series[0].Points[(int)Math.Max(e.ChartArea.CursorX.Position - 1, 0)];
   // do what is need with the data point
   pt.MarkerStyle = MarkerStyle.Square; 
}

这显然假设图表区域中只有一个系列。

如果需要,请使用HitTestResult的ChartElementType

HitTestResult result = chart.HitTest(e.X, e.Y);

if (result.ChartElementType == ChartElementType.DataPoint)
{
    int index = result.PointIndex;
    // todo something...
}

您好,我的序列有实际的x值,它是基于时间的,但间隔不一致(固定)。如何找到最近的点?我们能知道所有点的位置吗?这样我们就可以通过迭代找到最近的一个点?