Jake
Jake

Reputation: 49

How can you use LiveCharts observablepoint with datetimes for the xaxis?

Using livecharts https://lvcharts.net/App/examples/v1/Wpf/Observable%20Point how can I have the x-axis label or value be a datetime?

Upvotes: 0

Views: 1002

Answers (1)

BionicCode
BionicCode

Reputation: 28968

Since ObservablePoint only accepts double values, you must convert the DateTime to ticks. Then define a label formatter that knows how to convert ticks to a DateTime string:

ChartViewModel.cs

class ChartViewModel : INotifyPropertyChanged
{
  public ChartViewModel()
  {
    this.SeriesValues = new ChartValues<ObservablePoint>
    {
      new ObservablePoint(DateTime.Now.Ticks, 21),
      new ObservablePoint(DateTime.Now.AddDays(6).Ticks, 51),
      new ObservablePoint(DateTime.Now.AddDays(7).Ticks, 61),
      new ObservablePoint(DateTime.Now.AddDays(8).Ticks, 81),
      new ObservablePoint(DateTime.Now.AddDays(7).Ticks, 81),
      new ObservablePoint(DateTime.Now.AddDays(10).Ticks, 81),
      new ObservablePoint(DateTime.Now.AddDays(9).Ticks, 51)
    };
  }

  private static string ConvertTicksToDateTimeString(double value) 
    => new DateTime((long)value).ToString();

  public ChartValues<ObservablePoint> SeriesValues { get; }
  public Func<double, string> LabelFormatter => ConvertTicksDateTimeString;
}

MainWindow.xaml

<Window>
  <Window.DataContext>
    <ChartViewModel />
  </Window.DataContext>

  <lvc:CartesianChart Height="200">
    <lvc:CartesianChart.Series>
      <lvc:LineSeries Values="{Binding SeriesValues}"
                      Fill="LightBlue" />
    </lvc:CartesianChart.Series>

    <lvc:CartesianChart.AxisX>
      <lvc:Axis LabelFormatter="{Binding LabelFormatter}" />
    </lvc:CartesianChart.AxisX>
  </lvc:CartesianChart>
</Window>

Upvotes: 1

Related Questions