答案 0 :(得分:0)
以下是我在评论中提到的粗略计算:
首先,我们使用一个将Legend.Position
从百分比转换为像素的函数:
RectangleF LegendClientRectangle(Chart chart, Legend L)
{
RectangleF LAR = L.Position.ToRectangleF();
float pw = chart.ClientSize.Width / 100f;
float ph = chart.ClientSize.Height / 100f;
return new RectangleF(pw * LAR.X, ph * LAR.Y, pw * LAR.Width, ph * LAR.Height);
}
接下来,我们对MouseClick
进行编码,以获取属于点击位置的Series
:
private void chart1_MouseClick(object sender, MouseEventArgs e)
{
Point mp = e.Location;
Legend L = chart1.Legends[0];
RectangleF LCR = LegendClientRectangle(chart1, L);
if ( LCR.Contains(mp) )
{
int yh = (int) (LCR.Height / chart1.Series.Count);
int myRel = (int)(mp.Y - LCR.Y);
int ser = myRel / yh; // <--- this is the series index
Series S = chart1.Series[ser]; // add check here!
// decide which you have set and want to use..:
string text = S.LegendText != "" ? S.LegendText : S.Name;
Console.WriteLine("Series # " + ser + " -> " + text);
}
}
请注意,此代码假定只有一列图例项没有额外内容,例如图例标题.. 如果布局有更多列或是基于行的布局,则必须调整代码,可能不是那么简单..
另请注意,LegendItem
中的文字可以单独设置,也可以是默认设置,即Series.Name
。您应该知道或测试LegendText
是否已设置!
<强>更新强>
我想知道为什么我没有简单地使用HitTest
作为答案:
private void chart1_MouseClick(object sender, MouseEventArgs e)
{
HitTestResult hit = chart1.HitTest(e.X, e.Y);
Series s = null;
if (hit != null) s = hit.Series;
if (s != null)
{
string text = s.LegendText != "" ? s.LegendText : s.Name;
Console.WriteLine("Series # " + chart1.Series.IndexOf(s) + " -> " + text);
}
}