饼图切片单击

时间:2017-03-02 18:33:30

标签: c# winforms data-visualization pie-chart

我正在尝试点击我的饼图,我从Windows形式的工具箱中为C#吸毒,​​并显示该切片的详细信息。现在这是我点击的代码。我想知道这是否是正确的路线或我应该走的路线。

private void chart1_Click(object sender, EventArgs e)
{
    HitTestResult results = chart1.HitTest((e as MouseEventArgs).X, (e as MouseEventArgs).Y);
}

我也是using System.Windows.Forms.DataVisualization.Charting;

3 个答案:

答案 0 :(得分:8)

是的,这是正确的方法。

您现在可以测试DataPoint是否有效等。

我会使用MouseClick btw,默认情况下为MouseEventArgs

您甚至可以对MouseMove事件进行编码,并使用相同的hittest来控制光标以显示用户在数据点上...

以下是一个例子:

private void chart1_MouseClick(object sender, MouseEventArgs e)
{
    HitTestResult hit = chart1.HitTest(e.X, e.Y, ChartElementType.DataPoint);

    if (hit.PointIndex >= 0 && hit.Series != null)
    {
        DataPoint dp = chart1.Series[0].Points[hit.PointIndex];
        label1.Text = "Value #" + hit.PointIndex + " = " + dp.XValue;
    }
    else label1.Text = "";
}

private void chart1_MouseMove(object sender, MouseEventArgs e)
{
    HitTestResult hit = chart1.HitTest(e.X, e.Y);
    var dp = hit.Object as DataPoint;
    Cursor = (dp is null) ? Cursors.Default : Cursors.Hand;
}

请注意,这两个事件使用不同的方式来测试命中..!

enter image description here

答案 1 :(得分:1)

我喜欢接受的答案。但是这里有一个稍微不同的方法,它使用通用代码进行命中测试,还支持悬停和点击图例中的项目。

private int pieHitPointIndex(Chart pie, MouseEventArgs e)
{
    HitTestResult hitPiece = pie.HitTest(e.X, e.Y, ChartElementType.DataPoint);
    HitTestResult hitLegend = pie.HitTest(e.X, e.Y, ChartElementType.LegendItem);
    int pointIndex = -1;
    if (hitPiece.Series != null) pointIndex = hitPiece.PointIndex;
    if (hitLegend.Series != null) pointIndex = hitLegend.PointIndex;
    return pointIndex;
}
private void pie_MouseClick(object sender, MouseEventArgs e)
{
    Chart pie = (Chart)sender;
    int pointIndex = pieHitPointIndex(pie, e);
    if (pointIndex >= 0)
    {
        DataPoint dp = pie.Series[0].Points[pointIndex];
        // do what you want to do with a click
    }
}
private void pie_MouseMove(object sender, MouseEventArgs e)
{
    Chart pie = (Chart)sender;
    int pointIndex = pieHitPointIndex(pie, e);
    if (pointIndex >= 0)
    {
        Cursor = Cursors.Hand;
    }
    else
    {
        Cursor = Cursors.Default;
    }
}

答案 2 :(得分:0)

public class CustomChart : Chart
{
    public CustomChart()
    : base()
    {
        // Prevent the button from drawing its own border
        SetStyle(ControlStyles.Selectable, false);
    }
}