MS图表,如何在鼠标移动事件中获取CursorX数据点

本文关键字:事件 获取 CursorX 数据 移动 鼠标 图表 MS | 更新日期: 2023-09-27 18:24:30

我有一个关于ms图表的问题:如何在鼠标移动事件中获得CursorX数据点?

MS图表,如何在鼠标移动事件中获取CursorX数据点

假设您的图表名为_chart,并且您所追求的图表的索引为CHART_INDEX:

首先,根据X像素坐标计算X轴坐标:

// Assume MouseEventArgs e is passed in from (for example) chart_MouseDown():
var xAxis = _chart.ChartAreas[CHART_INDEX].AxisX;
double x = xAxis.PixelPositionToValue(e.Location.X);

现在x是X轴上像素的X坐标(以X轴为单位)。

然后,您必须根据X轴值确定最近的前一个数据点。

假设SERIES_INDEX是您感兴趣的系列的索引:

private double nearestPreceedingValue(double xCoord)
{
    // Find the last  at or before the current xCoord.
    // Since the data is ordered on X, we can binary search for it.
    var data  = _chart.Series[SERIES_INDEX].Points;
    int index = data.BinarySearch(xCoord, (xVal, point) => Math.Sign(xCoord - point.XValue));
    if (index < 0)
    {
        index = ~index;               // BinarySearch() returns the index of the next element LARGER than the target.
        index = Math.Max(0, index-1); // We want the value of the previous element, so we must decrement the returned index.
    }                                 // If this is before the start of the graph, use the first valid data point.
    // Return -1 if not found, or the value of the nearest preceeding point if found.
    // (Substitute an appropriate value for -1 if you need a different "invalid" value.)
    return (index < data.Count) ? (int)data[index].YValues[0] : -1;
}