自定义和事件

在图表控件中,可以使用事件来自定义图表行为,例如执行自定义绘制。 ASP.NET 和 Windows 窗体的图表控件公开不同的事件组。 有关每个控件的完整事件列表,请参见 ChartChart

PrePaint 和 PostPaint

PrePaintPostPaint 事件是最常用的事件。 在绘制每个图表元素之前和之后将分别触发这两个事件。

备注

若为图表区域启用三维,则不会为 Series 对象触发这两个事件。

若要确定为哪个图表元素触发了当前事件,请使用 ChartPaintEventArgs.ChartElement 属性。

下面的事件处理程序将在绘制 Series 元素并强调名为“Product F”的数据点后,绘制六个同心圆。

Private Sub chart1_PostPaint(ByVal sender As Object, ByVal e As ChartPaintEventArgs) 

   If TypeOf e.ChartElement Is Series Then 
      Dim series As Series = DirectCast(e.ChartElement, Series) 
      Dim position As System.Drawing.PointF = System.Drawing.PointF.Empty 

      ' Find data point with label "Product F". 
      For Each point As DataPoint In series.Points 
         position.X += 1 
         
         If point.AxisLabel = "Product F" Then 
            position.Y = CSng(point.YValues(0)) 
            Exit For 
         End If 
      Next 

      ' Get relative coordinates of the data point values found. 
      position.X = CSng(e.ChartGraphics.GetPositionFromAxis("Default", AxisName.X, position.X)) 
      position.Y = CSng(e.ChartGraphics.GetPositionFromAxis("Default", AxisName.Y, position.Y)) 
      
      ' Convert relative coordinates to absolute coordinates. 
      position = e.ChartGraphics.GetAbsolutePoint(position) 
      
      ' Draw custom object. 
      For radius As Integer = 20 To 79 Step 10 
         e.ChartGraphics.Graphics.DrawEllipse(System.Drawing.Pens.Red, position.X - radius / 2, _
            position.Y - radius / 2, radius, radius) 
      Next 
   End If 
End Sub
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
   if (e.ChartElement is Series)
   {
      Series series = (Series)e.ChartElement;
      System.Drawing.PointF position = System.Drawing.PointF.Empty;
      // Find data point with label "Product F".
      foreach (DataPoint point in series.Points)
      {
         ++position.X;

         if (point.AxisLabel == "Product F")
         {
            position.Y = (float)point.YValues[0];
            break;
         }
      }
      // Get relative coordinates of the data point values found.
      position.X = (float)e.ChartGraphics.GetPositionFromAxis("Default", AxisName.X, position.X);
      position.Y = (float)e.ChartGraphics.GetPositionFromAxis("Default", AxisName.Y, position.Y);

      // Convert relative coordinates to absolute coordinates.
      position = e.ChartGraphics.GetAbsolutePoint(position);

      // Draw custom object.
      for (int radius = 20; radius < 80; radius += 10)
      {
         e.ChartGraphics.Graphics.DrawEllipse(System.Drawing.Pens.Red, position.X - radius / 2, 
                                              position.Y - radius / 2, radius, radius);
      }
   }
}

请参见

其他资源

高级主题