WPF使用LiveCharts画图时,横坐标转换成时间

一、背景

使用LiveCharts画图时,横坐标通常为数值类型,要转换成时间等自定义类型,需要用到Formatter进行类型转换。

示例使用MVVM模式编写

二、View代码

关键是设置LabelFormatter属性

复制代码
<lvc:CartesianChart Series="{Binding Series}">
            <lvc:CartesianChart.AxisX>
                <lvc:Axis LabelFormatter="{Binding Formatter}"></lvc:Axis>
            </lvc:CartesianChart.AxisX>
</lvc:CartesianChart>

三、Model代码

cs 复制代码
 public class DataPoint
    {
        public DateTime Date { get; set; }
        public double Value { get; set; }
    }

四、ViewModel代码

4.1 设置数据映射

用Mappers将DateTime转换数值类型,这里使用了DateTime的Ticks进行转换

cs 复制代码
var dayConfig = Mappers.Xy<DataPoint>()
                 .X(dayModel => (double)dayModel.Date.Ticks / TimeSpan.FromHours(1).Ticks)
                 .Y(dayModel => dayModel.Value);

4.2 设置数据映射转换格式

将转换后的数值类型还原成Datetime,再加上自定义的字符

cs 复制代码
Formatter = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("t");

4.3 后端代码

cs 复制代码
public ScatterChartViewModel()
        {
            // 初始化数据
            var dataPoints = new List<DataPoint>
        {
            new DataPoint { Date = new DateTime(2024, 3, 1), Value = 10 },
            new DataPoint { Date = new DateTime(2024, 3, 2), Value = 20 },
            new DataPoint { Date = new DateTime(2024, 3, 3), Value = 15 },
            // 添加更多数据点
        };


            var dayConfig = Mappers.Xy<DataPoint>()
                 .X(dayModel => (double)dayModel.Date.Ticks / TimeSpan.FromHours(1).Ticks)
                 .Y(dayModel => dayModel.Value);

            Series = new SeriesCollection(dayConfig)
            {
                new ScatterSeries
                {
                    Title = "Data Points",
                    Values = new ChartValues<DataPoint>(dataPoints)
                }
            };

            Formatter = value => new DateTime((long)(value * TimeSpan.FromHours(1).Ticks)).ToString("t");
        }
相关推荐
WineMonk8 小时前
WPF 力导引算法实现图布局
算法·wpf
FuckPatience15 小时前
WPF 国际化ResXManager的使用-梳理
wpf
武藤一雄16 小时前
Avalonia与WPF的差异及避坑指南 (持续更新)
前端·前端框架·c#·.net·wpf·avalonia
ou.cs18 小时前
WPF OxyPlot 时间轴完美显示! X 轴精准显示 时:分 格式(含完整源码)
c#·wpf
5008418 小时前
鸿蒙 Flutter 分布式安全:软总线加密通信与设备互信认证
分布式·安全·flutter·华为·架构·wpf·开源鸿蒙
跟着珅聪学java1 天前
RedisTemplate 分布式锁实现详解
wpf
武藤一雄1 天前
C#:进程/线程/多线程/AppDomain详解
后端·微软·c#·asp.net·.net·wpf·.netcore
武藤一雄2 天前
C# Prism框架详解
开发语言·后端·微软·c#·.net·wpf
wniuniu_2 天前
ceph基础知识
ceph·wpf
DataIntel2 天前
WPF 操作之Dispatcher--- 只在多线程更新 UI 时使用。
wpf