c# - 当鼠标在点上时查看图表点的值

标签 c# winforms mschart

我有一个图表,我希望用户在指针位于点上时看到值。 通过在页面 finding the value of the points in a chart 中使用 digEmAll 的帮助,我可以写出下面的代码:

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";          
        }    
    } 
} 

通过上面的代码,当指针接近时,用户可以看到值。但是现在如何让用户只在指针时才能看到值论点? 我换了

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

代替

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

解决了我的问题。但是没有用。

最佳答案

你应该这样修改代码:

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);
                }
            }
        }
    }
}

想法是检查鼠标是否非常靠近该点,例如2 像素(因为不太可能完全在该点上)并在这种情况下显示工具提示。

Here's a complete working example.

关于c# - 当鼠标在点上时查看图表点的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10648828/

相关文章:

c# - 如何将 SRP 应用于用户界面类?

c# - DataPointCollection 清除性能

c# - Microsoft 图表控件和 X 轴时间刻度格式

asp.net - 在图表中显示图例

c# - 线程中使用的 DataTable 内部索引已损坏 : '5' .

c# - 学习 C#,数学方程未按预期结果

c# - 存储常用数据库表 ID 的最佳方法?

c# - WPF 中的 OuterGlow 效果不适用于分层窗口?

c# - 用于检测 ISO 语言代码的正则表达式

c# - 带有计时器的简单应用程序正在消耗内存?