Spline chart, how to get the clicked item? [duplic

2019-09-10 10:29发布

This question already has an answer here:

I'm working whit charts on c#.

I would like to know a way of get the iten (the spline) clicked on the chart to do something like change color or hide.

enter image description here

1条回答
小情绪 Triste *
2楼-- · 2019-09-10 11:00

You can check the clicked item using HitTest, as suggested..:

private void chart1_MouseDown(object sender, MouseEventArgs e)
{
    HitTestResult result = chart1.HitTest(e.X, e.Y);
    // now do what you want with the data..:
    if (result.Series != null && result.PointIndex >= 0)
        Text = "X = " + result.Series.Points[result.PointIndex].XValue + 
            "   Y = " + result.Series.Points[result.PointIndex].YValues[0];
}

To help the user you can indicate a possible hit:

private void chart1_MouseMove(object sender, MouseEventArgs e)
{
    HitTestResult result = chart1.HitTest(e.X, e.Y);
    Cursor = result.Series != null ? Cursors.Hand : Cursors.Default;
}

Do your users a favor by making the spline lines a little larger:

eachOfYourSeries.BorderWidth = 4;

Of course the chart you show makes a controlled clicking impossible without zooming in first..

Now if all you want is hiding a Series or changing its Color the HitTestResult is good enough:

 result.Series.Enabled = flase;

or

 result.Series.Color = Color.Fuchsia;

But to access the clicked values, it may not be..:

Note that especially a Spline or a Line graph, need only very few DataPoints to create their lines; so the result from HitTest simply is not enough; it will tell you which series was clicked and also the closest DataPoint but to get at the correct values you still may need to convert the pixels to data values.

So instead of the HitTest result you may prefer to use the handy function PixelPositionToValue:

 float px = (float)yourChartArea.AxisX.PixelPositionToValue(e.X);

This will get all the values between the actual DataPoints. Of course you can do the same for the Y-Values:

 float py = (float)yourChartArea.AxisY.PixelPositionToValue(e.Y);

Note that you can only use these function when the chart is not busy with determining the layout; officially this is only during any of the three Paint events. But I found that in practice a mouse event is also fine. You will get a null value when the chart is not ready..

查看更多
登录 后发表回答