2012-05-18 16 views
11

Tengo un gráfico y quiero que el usuario vea los valores cuando el puntero está en los puntos. Mediante el uso de la ayuda de digEmAll en la página finding the value of the points in a chart, podría escribir el siguiente código:ver los valores de los puntos del gráfico cuando el mouse está en los puntos

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)   
     {    
      chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY";   
     }  
    } 
} 

por el código anterior, el usuario puede ver los valores cuando el puntero es cerca de un series.But ahora ¿Cómo puede Dejo que el usuario vea los valores solo cuando el puntero es en los puntos? que sustituyen

int k = result.PointIndex; 
if (k >= 0) 
{ 
    chart1.Series[0].Points[k].ToolTip = "X=#VALX, Y=#VALY"; 
} 

en lugar de

chart1.Series[0].ToolTip = "X=#VALX, Y=#VALY"; 

a resolver mi problema.Pero No fue muy útil.

Respuesta

18

Debe modificar el código de esta manera:

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.DataPoint); 
    foreach (var result in results) 
    { 
     if (result.ChartElementType == ChartElementType.DataPoint) 
     { 
      var prop = result.Object as DataPoint; 
      if (prop != null) 
      { 
       var pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(prop.XValue); 
       var pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(prop.YValues[0]); 

       // check if the cursor is really close to the point (2 pixels around the point) 
       if (Math.Abs(pos.X - pointXPixel) < 2 && 
        Math.Abs(pos.Y - pointYPixel) < 2) 
       { 
        tooltip.Show("X=" + prop.XValue + ", Y=" + prop.YValues[0], this.chart1, 
            pos.X, pos.Y - 15); 
       } 
      } 
     } 
    } 
} 

La idea es comprobar si el ratón está muy cerca del punto de, por ejemplo, 2 píxeles alrededor (porque es poco probable que sea exactamente en el punto) y muestre la información sobre herramientas en ese caso.

Here's a complete working example.

+1

Funcionando perfectamente para el eje primario. Pero la condición '(Math.Abs ​​(pos.X - pointXPixel) <2 && Math.Abs ​​(pos.Y - pointYPixel) <2)' falla para la serie de ejes secundarios. –

+0

@RameshDurai: sí, este código solo considera el eje primario. – digEmAll

7

Me gustaría tener esta solución:

Agregar controlador de eventos personalizado sobre herramientas:

this.chart1.GetToolTipText += this.chart1_GetToolTipText; 

Implementar controlador de eventos:

private void chart1_GetToolTipText(object sender, ToolTipEventArgs e) 
    { 
    // Check selected chart element and set tooltip text for it 
    switch (e.HitTestResult.ChartElementType) 
    { 
     case ChartElementType.DataPoint: 
      var dataPoint = e.HitTestResult.Series.Points[e.HitTestResult.PointIndex]; 
      e.Text = string.Format("X:\t{0}\nY:\t{1}", dataPoint.XValue, dataPoint.YValues[0]); 
      break; 
    } 
    } 
+0

He intentado con tu código. Aparece cuando mi mouse se desplaza sobre el gráfico pero no aparece información sobre herramientas. –

+0

@M_Mogharrabi: No puedo probarlo todavía, pero de mi memoria: - Debe mostrar los "marcadores de punto" - No configure la propiedad ToolTip del punto de datos, consulte https://stackoverflow.com/questions/ 14256283/show-tooltip-only-on-the-datapoint-for-line-graph-in-mschart – jreichert

Cuestiones relacionadas