Hit testing is done with the HitTest method. You must give a point for which to test and the method will return a list of the ChartElement objects that contain this point. The ChartElement can be either Bar, Line or PieSlice. Each ChartElement has Index and SeriesIndex properties, which allow you to recognize the series that this chart element belongs to.
The location of the data that the ChartElement represents in the data list for the series can be get with the Bar.BarIndex, PieSlice.SliceIndex and Line.Points properties.
The following code tests which bar the user has clicked. It uses the MouseDown event:
C#
Copy Code
|
---|
private void barChart1_MouseDown(object sender, MouseButtonEventArgs e) { List<ChartElement> result = barChart1.HitTest(e.GetPosition(barChart1));
if (result.Count > 0) { foreach (ChartElement element in result) { if (element is Bar) { Bar bar = element as Bar; BarSeries series = barChart1.Series[bar.SeriesIndex] as BarSeries; double yData = (double)series.YData[bar.BarIndex]; double xData = (double)series.XData[bar.BarIndex]; } } } } |
VB.NET
Copy Code
|
---|
Private Sub barChart1_MouseDown(sender As Object, e As MouseButtonEventArgs)
Dim result As List(Of ChartElement) = barChart1.HitTest(e.GetPosition(barChart1))
If result.Count > 0 Then For Each element As ChartElement In result If TypeOf element Is Bar Then Dim bar As Bar = TryCast(element, Bar) Dim series As BarSeries = TryCast(barChart1.Series(bar.SeriesIndex), BarSeries) Dim yData As Double = CDbl(series.YData(bar.BarIndex)) Dim xData As Double = CDbl(series.XData(bar.BarIndex)) End If Next End If
End Sub |