我有一个LineSeries图表。通过series.IsSelectionEnabled = true;
当我将鼠标移动到点上时,我可以选择该节点。但是当鼠标没有完全超过该点但是在它附近(上方或下方)时,我怎么能这样做呢?感谢。
PS: 还有一件事。如何在鼠标悬停时更改列的颜色,以便用户可以分辨出他/她要选择哪一列。
答案 0 :(得分:1)
我已使用单个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;
我写过评论,但如果事情不清楚,你可以问我,我会解释。