[英]Select the nearest point in a Silverlight Toolkit chart
我有一個LineSeries圖表。 按系列series.IsSelectionEnabled = true;
當我將鼠標移到這些點上時,可以選擇該節點。 但是,當鼠標不完全在該點上但它在它附近(上方或下方)時,我該怎么辦? 謝謝。
PS:還有一件事。 當鼠標懸停在列上時,如何更改其顏色,以便用戶可以知道他/她將選擇哪個列。
我用單個LineSeries
創建了圖表示例。 您可以在圖上的任意位置單擊,然后將選擇最近的點。
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;
我已經寫了評論,但是如果不清楚,您可以提出要求,我會解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.