Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This code sample describes how to show a tooltip owhen the mouse cursor hovers a data.point.
- // How To Run:
- // 1 - Create a WinForms project called WinFormTests
- // 2 - Double-click on Form1, add a MS chart (Dock = Fill)
- // 3 - Open Form1.cs and copy and paste the following code
- // 4 - Build and run
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Windows.Forms;
- using System.Windows.Forms.DataVisualization.Charting;
- namespace WinFormTests
- {
- public partial class Form1 : Form
- {
- internal class Item
- {
- public double X { get; private set; }
- public double Y { get; private set; }
- public Item(double x, double y)
- {
- this.X = x;
- this.Y = y;
- }
- }
- public Form1()
- {
- InitializeComponent();
- this.chart1.MouseMove += new MouseEventHandler(chart1_MouseMove);
- this.tooltip.AutomaticDelay = 10;
- FillChart();
- }
- private void FillChart()
- {
- var rand = new Random(123);
- var items = Enumerable.Range(0, 20).Select(x => new Item(x, rand.Next(1, 100) / 2.0)).ToList();
- this.chart1.Series.Clear();
- var seriesLines = this.chart1.Series.Add("Line");
- seriesLines.ChartType = SeriesChartType.Line; //System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
- seriesLines.XValueMember = "X";
- seriesLines.YValueMembers = "Y";
- seriesLines.Color = Color.Red;
- var seriesPoints = this.chart1.Series.Add("Points");
- seriesPoints.ChartType = SeriesChartType.Point; //System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
- seriesPoints.XValueMember = "X";
- seriesPoints.YValueMembers = "Y";
- this.chart1.DataSource = items;
- }
- Point? prevPosition = null;
- ToolTip tooltip = new ToolTip();
- void chart1_MouseMove(object sender, MouseEventArgs e)
- {
- var pos = e.Location;
- if (prevPosition.HasValue && pos == prevPosition.Value)
- return;
- tooltip.RemoveAll();
- prevPosition = pos;
- var results = chart1.HitTest(pos.X, pos.Y, false,
- ChartElementType.DataPoint);
- foreach (var result in results)
- {
- if (result.ChartElementType == ChartElementType.DataPoint)
- {
- var prop = result.Object as DataPoint;
- if (prop != null)
- {
- var pointXPixel = result.ChartArea.AxisX.ValueToPixelPosition(prop.XValue);
- var pointYPixel = result.ChartArea.AxisY.ValueToPixelPosition(prop.YValues[0]);
- // check if the cursor is really close to the point (2 pixels around)
- if (Math.Abs(pos.X - pointXPixel) < 2 &&
- Math.Abs(pos.Y - pointYPixel) < 2)
- {
- tooltip.Show("X=" + prop.XValue + ", Y=" + prop.YValues[0], this.chart1,
- pos.X, pos.Y - 15);
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement