我对ms图表有疑问:如何在鼠标移动事件中获取CursorX数据点?
答案 0 :(得分:0)
假设您的图表名为_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;
}