找到图表中点的值

时间:2012-03-10 15:36:31

标签: c# winforms mschart

我在表格上制作了一张图表。

我希望用户通过点击该部分来查看气球中每个部分的valuex_valuey_value

当用户移动鼠标时,气球会消失。

我该怎么做?

1 个答案:

答案 0 :(得分:11)

你可以这样做:

    ToolTip tooltip = new ToolTip();
    Point? clickPosition = null;

    void chart1_MouseMove(object sender, MouseEventArgs e)
    {
        if (clickPosition.HasValue && e.Location != clickPosition)
        {
            tooltip.RemoveAll();
            clickPosition = null;
        }
    }

    void chart1_MouseClick(object sender, MouseEventArgs e)
    {
        var pos = e.Location;
        clickPosition = pos;
        var results = chart1.HitTest(pos.X, pos.Y, false,
                                     ChartElementType.PlottingArea);
        foreach (var result in results)
        {
            if (result.ChartElementType == ChartElementType.PlottingArea)
            {
                var xVal = result.ChartArea.AxisX.PixelPositionToValue(pos.X);
                var yVal = result.ChartArea.AxisY.PixelPositionToValue(pos.Y);

                tooltip.Show("X=" + xVal + ", Y=" + yVal, 
                             this.chart1, e.Location.X,e.Location.Y - 15);
            }
        }
    }

结果:

enter image description here

编辑:

在鼠标移动时显示工具提示,您可以使用以下代码:

Point? prevPosition = null;
ToolTip tooltip = new ToolTip();

void chart1_MouseMove(object sender, MouseEventArgs e)
{
    var pos = e.Location;
    if (prevPosition.HasValue && pos == prevPosition.Value)
        return;
    tooltip.RemoveAll();
    prevPosition = pos;
    var results = chart1.HitTest(pos.X, pos.Y, false, 
                                 ChartElementType.PlottingArea);
    foreach (var result in results)
    {
        if (result.ChartElementType == ChartElementType.PlottingArea)
        {
            var xVal = result.ChartArea.AxisX.PixelPositionToValue(pos.X);
            var yVal = result.ChartArea.AxisY.PixelPositionToValue(pos.Y);

            tooltip.Show("X=" + xVal + ", Y=" + yVal, this.chart1, 
                         pos.X, pos.Y - 15);
        }
    }
}

请注意,这会在图表的任何位置显示工具提示。如果只想在鼠标接近连续点时显示它,则可以使用mschart功能,例如:

yourSeries.ToolTip = "X=#VALX, Y=#VALY";

(进一步的例子here