问题描述
|
我有一个Lineseries图表。当我将鼠标移到这些点上时,通过
series.IsSelectionEnabled = true;
,可以选择该节点。但是,当鼠标不完全在该点上而是它在它附近(上方或下方)时,我该怎么办?谢谢。
PS:
还有一件事。当鼠标悬停在列上时,如何更改其颜色,以便用户知道他/她将选择哪一列。
解决方法
我创建了带有单个“ 1”的图表示例。您可以在图上的任意位置单击,然后将选择最近的点。
XAML(将
ItemsSource
属性和其他属性更改为您的属性):
<Charting:Chart MouseLeftButtonDown=\"Chart_MouseLeftButtonDown\">
<Charting:Chart.Series>
<Charting:LineSeries IsSelectionEnabled=\"True\" ItemsSource=\"...\" ... />
</Charting:Chart.Series>
</Charting:Chart>
后台代码:
private void Chart_MouseLeftButtonDown(object sender,MouseButtonEventArgs e)
{
var chart = sender as Chart;
//In my example the line series is the first item of the chart series
var line = (LineSeries)chart.Series[0];
//Find the nearest point on the LineSeries
var newPoint = e.GetPosition(line);
var selectIndex = this.FindNearestPointIndex(line.Points,newPoint);
if (selectIndex != null)
{
//Select a real item from the items source
var source = line.ItemsSource as IList;
line.SelectedItem = source[selectIndex.Value];
}
}
private int? FindNearestPointIndex(PointCollection points,Point newPoint)
{
if (points == null || !points.Any())
return null;
//c^2 = a^2+b^2
Func<Point,Point,double> getLength = (p1,p2) => Math.Sqrt(Math.Pow(p1.X - p2.X,2) + Math.Pow(p1.Y - p2.Y,2));
//Create the collection of points with more information
var items = points.Select((p,i) => new { Point = p,Length = getLength(p,newPoint),Index = i });
var minLength = items.Min(item => item.Length);
//Uncomment if it is necessary to have some kind of sensitive area
//if (minLength > 50)
// return null;
//The index of the point with min distance to the new point
return items.First(item => item.Length == minLength).Index;
}
正如我所说的,即使您单击距离任何图表点很远的地方,该图表也会选择最近的点。如果这不是预期的行为,则可以取消注释这些行,并以像素为单位设置任何数字:
//Uncomment if it is necessary to have some kind of sensitive area
if (minLength > 50)
return null;
我已经写过评论,但是如果不清楚,您可以提问,我会解释。