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");
        }
相关推荐
dalong1010 小时前
WPF:箭头绘制程序
wpf·自定义绘制
张工在路上1 天前
WPF 布局基础概述
大数据·hadoop·wpf
迪飞特科技2 天前
分布式事务下 Spring 声明式事务失效的 3 种修复方案
分布式·spring·wpf
2601_962174175 天前
Redis 简介
数据库·redis·wpf
SamChan906 天前
Python+PyMuPDF提取PDF表格并翻译:表格结构检测与双语重建实战
windows·python·ai·pdf·wpf
SamChan906 天前
Python+OpenCV检测PDF翻译后排版偏移:像素级格式一致性验证
python·opencv·ai·pdf·wpf
FuckPatience6 天前
WPF 拿到控件的最初样式,修改获得焦点样式
wpf
主宰者6 天前
【WPF】MainWindow前添加加载窗口,发现加载过程中有白色无内容窗口闪烁一下的解决方案
wpf
Vae_Mars7 天前
WPF中的ControlTemplate(控件模板)
wpf
SamChan907 天前
Python+ReportLab自动生成PDF翻译质量审计报告:从数据到可视化的完整方案
开发语言·python·ai·pdf·wpf