When showing time series data with the time dimension along the x axis, how could i get the corresponding date when the user clicks on the graph?
Hi Mark,
Thank you for your posts. I am glad that you have managed to resolve your issue. I believe that other members of our community could get benefit from this.
private void theChart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var chart = (XamDataChart)sender; var s = chart.Series.FirstOrDefault(); if (s == null) return; var position = e.GetPosition(s); var xAxis = theChart.Axes.OfType<CategoryXAxis>().First(); var yAxis = theChart.Axes.OfType<NumericYAxis>().First(); var viewport = new Rect(0, 0, xAxis.ActualWidth, yAxis.ActualHeight); var window = s.SeriesViewer.WindowRect;
var scalerParams = new ScalerParams(window, viewport, false);
var unscaledX = xAxis.GetUnscaledValue(position.X, scalerParams); var unscaledY = yAxis.GetUnscaledValue(position.Y, scalerParams);
var index = (int)Math.Floor(unscaledX);
var idx = 0; var iEnumerable = s.ItemsSource.GetEnumerator(); var item = default(ChartData); while (iEnumerable.MoveNext()) { if (idx == index) { item = (ChartData)iEnumerable.Current; break; }
idx++; }
Console.WriteLine(item.Date); } }
public class ChartData { public DateTime Date { get; set; } public double Value1 { get; set; } public double Value2 { get; set; } public double Value3 { get; set; }
public static ObservableCollection<ChartData> GenerateData(int count) { ObservableCollection<ChartData> data = new ObservableCollection<ChartData>();
Random r = new Random();
ChartData data0 = new ChartData { Date = DateTime.Now, Value1 = r.Next(20, 40), Value2 = r.Next(20, 40), Value3 = r.Next(20, 40), };
data.Add(data0);
for (int i = 1; i < count; i++) { ChartData dat = new ChartData { Date = DateTime.Now.AddDays(i), };
if (r.NextDouble() > .5) { dat.Value1 = data[i - 1].Value1 + r.NextDouble(); dat.Value2 = data[i - 1].Value2 + r.NextDouble(); dat.Value3 = data[i - 1].Value3 + r.NextDouble(); } else { dat.Value1 = data[i - 1].Value1 - r.NextDouble(); dat.Value2 = data[i - 1].Value2 - r.NextDouble(); dat.Value3 = data[i - 1].Value3 - r.NextDouble(); }
data.Add(dat); }
return data; } }