You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LiveCharts折线图中使用DateTimePoint

解决LiveCharts 2中使用DateTime作为X轴的折线图问题

核心问题分析

你当前的代码存在两处关键错误:

  • 错误尝试直接访问chartPoint.x/chartPoint.y属性,LiveCharts 2中需通过chartPoint.Coordinate设置坐标值
  • 未配置X轴为时间类型,导致框架无法正确解析和显示DateTime格式的轴数据

修正后的实现代码

ViewModel 部分

public partial class ExampleViewModel : ObservableObject
{
    public ExampleViewModel()
    {
        using var streamReader = new StreamReader("data.json");
        var samples = JsonSerializer.Deserialize<TempList[]>(streamReader.ReadToEnd());

        Series = new ObservableCollection<ISeries>
        {
            new LineSeries<TempList>
            {
                Values = samples,
                // 正确映射DateTime到X轴坐标:将DateTime转为OADate(LiveCharts支持的double类型)
                Mapping = (sample, chartPoint) =>
                {
                    chartPoint.Coordinate = new(sample.Time.ToOADate(), sample.Temperature);
                },
                Fill = null
            }
        };

        // 配置轴:设置X轴为时间轴并自定义显示格式
        Axes = new ObservableCollection<Axis>
        {
            new Axis
            {
                // 将X轴的OADate数值转回DateTime并格式化显示
                Labeler = value => DateTime.FromOADate(value).ToString("yyyy-MM-dd HH:mm"),
                Name = "Time",
                NameTextSize = 14
            },
            new Axis
            {
                Name = "Temperature",
                NameTextSize = 14
            }
        };
    }

    public ObservableCollection<ISeries> Series { get; set; }
    public ObservableCollection<Axis> Axes { get; set; } // 添加轴配置属性

    public class TempList
    {
        public int Temperature { get; set; }
        public int TimeInt { get; set; }
        public DateTime Time { get; set; }
    }
}

XAML 部分(需在Chart控件中绑定Axes)

<UserControl x:Class="YourNamespace.YourView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF">
    <Grid>
        <lvc:CartesianChart
            Series="{Binding Series}"
            Axes="{Binding Axes}">
        </lvc:CartesianChart>
    </Grid>
</UserControl>

关键说明

  1. DateTime转数值:LiveCharts的轴底层使用double类型存储数据,因此需要将DateTime转为double,推荐使用ToOADate()方法,它能完整保留日期时间信息且转换可逆。
  2. 轴标签格式化:通过Axis.Labeler将X轴的double值(OADate格式)转回DateTime,并设置符合需求的显示格式(如yyyy-MM-dd HH:mm)。
  3. 简化数据模型:无需额外创建DateTimePoint类,直接映射TempList中的Time和Temperature字段即可,减少冗余代码。

内容的提问来源于stack exchange,提问作者Damo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:57:44