本文主要介绍如何给 C1Chart for Silverlight 添加鼠标跟踪行为,最终会显示一条垂直红线以及红线与各个系列的交点,主要步骤:
1、添加垂直线
2、添加垂直线和系列交点的显示
3、在鼠标移动时动态改变垂直线和交点标识的位置
-
public partial class MainPage : UserControl { ChartPanel pnl = new ChartPanel(); List<Ellipse> markers; public MainPage() { InitializeComponent(); AddLine(); AddMarkers(); chart.View.Layers.Add(pnl); chart.MouseMove += new MouseEventHandler(chart_MouseMove); } void AddLine() { Point p = new Point(0, double.NaN); var dt = (DataTemplate)Resources["line"]; var cpo = (ChartPanelObject)dt.LoadContent(); cpo.DataPoint = p; cpo.Action = ChartPanelAction.MouseMove; cpo.Attach = ChartPanelAttach.DataXY; pnl.Children.Add(cpo); } void AddMarkers() { markers = new List<Ellipse>(); for (int i = 0; i < chart.Data.Children.Count; i++) { Ellipse ep = new Ellipse(); ep.Width = 50; ep.Height = 50; ep.Stroke = new SolidColorBrush(Colors.Blue); ep.Fill = new SolidColorBrush(Color.FromArgb(64, 0, 0, 255)); markers.Add(ep); chart.View.Children.Add(ep); } } void SetMarkerPosition(Point pt) { double dis1; for (int i = 0; i < markers.Count; i++) { int p = chart.View.DataIndexFromPoint(pt, i, MeasureOption.X, out dis1); Point ps1 = chart.View.DataIndexToPoint(i, p); Canvas.SetLeft(markers[i], ps1.X - markers[i].Width / 2); Canvas.SetTop(markers[i], ps1.Y - markers[i].Height / 2); } } void chart_MouseMove(object sender, MouseEventArgs e) { SetMarkerPosition(e.GetPosition(this)); } } 复制代码
运行截图:
源码下载:VS2010 + Silverlight 5.0 + C1 Studio for Silverlight 2012V2