繁体   English   中英

在Silverlight工具包图表中选择最近的点

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM