[英]Select the nearest point in a Silverlight Toolkit chart
I have a LineSeries chart. 我有一个LineSeries图表。 By
series.IsSelectionEnabled = true;
按系列
series.IsSelectionEnabled = true;
when I move the mouse over the points, I can select that node. 当我将鼠标移到这些点上时,可以选择该节点。 But how can I do it when the mouse is not exactly over the point but when it's near it (above or under)?
但是,当鼠标不完全在该点上但它在它附近(上方或下方)时,我该怎么办? Thanks.
谢谢。
PS: One more thing. PS:还有一件事。 How can I change the color of the column when the mouse is over it so the user can tell which one of the columns he/she is going to select.
当鼠标悬停在列上时,如何更改其颜色,以便用户可以知道他/她将选择哪个列。
I have created the example of the chart with the single LineSeries
. 我用单个
LineSeries
创建了图表示例。 You can click anywhere at the plot and the nearest point will be selected. 您可以在图上的任意位置单击,然后将选择最近的点。
XAML (Change the ItemsSource
property and other properties to yours): XAML(将
ItemsSource
属性和其他属性更改为您的属性):
<Charting:Chart MouseLeftButtonDown="Chart_MouseLeftButtonDown">
<Charting:Chart.Series>
<Charting:LineSeries IsSelectionEnabled="True" ItemsSource="..." ... />
</Charting:Chart.Series>
</Charting:Chart>
Code-behind: 后台代码:
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;
}
As I said this chart will select the nearest point even if you click at a great distance away from any chart point. 正如我所说的,即使您单击距离任何图表点很远的地方,该图表也会选择最近的点。 If it isn't intended behavior, you can uncomment these lines and set any number in pixels:
如果这不是预期的行为,则可以取消注释这些行,并以像素为单位设置任何数字:
//Uncomment if it is necessary to have some kind of sensitive area
if (minLength > 50)
return null;
I have written comments, but if something isn't clear you can ask and I will explain. 我已经写了评论,但是如果不清楚,您可以提出要求,我会解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.