Spline chart, how to get the clicked item? [duplicate]

微笑、不失礼 提交于 2019-12-12 05:59:40

问题


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.


回答1:


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..



来源:https://stackoverflow.com/questions/36869585/spline-chart-how-to-get-the-clicked-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!