Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
225
DataPoint (really DataContext) on click?
posted

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?

Parents
No Data
Reply
  • 225
    Verified Answer
    posted

    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;
    }
    }

Children