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

如何为LiveCharts.WinForms.CartesianChart添加带提示的垂直标线

你当前的实现存在两个问题:一是错误新增了第二个X轴来放置垂直标线,会导致图表顶部出现多余的空白轴;二是没有将标线的Value值绑定到8月21日对应的X轴位置,也没有配置Tooltip属性。修正后的实现代码如下:

// 先查找8月21日在日期标签数组中的索引
int targetDateIndex = Array.IndexOf(myDateLabels, "8月21日");
// 容错处理,避免找不到对应日期时报错
targetDateIndex = targetDateIndex < 0 ? 0 : targetDateIndex;

// 直接在已使用的X轴上添加标线配置,不要新增第二个X轴
cartesianChart1.AxisX.Add(new Axis
{
    Labels = myDateLabels,
    Separator = new LiveCharts.Wpf.Separator { Step = 1 },
    LabelsRotation = 270,
    Sections = new SectionsCollection
    {
        new AxisSection
        {
            Stroke = System.Windows.Media.Brushes.Black,
            StrokeThickness = 1,
            // 绑定到8月21日对应的X轴位置
            Value = targetDateIndex,
            // 配置Tooltip提示内容
            ToolTip = "8月21日 标记线"
        }
    }
});

cartesianChart1.AxisY.Add(new Axis());
cartesianChart1.LegendLocation = LegendLocation.Bottom;
// 确保图表Tooltip功能启用
cartesianChart1.DataTooltip.Enabled = true;

SeriesCollection series = new SeriesCollection();
series.Add(new LineSeries 
{ 
    Title = "Sign Ups", 
    Values = signUpsValues, 
    Stroke = System.Windows.Media.Brushes.Blue, 
    Fill = System.Windows.Media.Brushes.Transparent 
});

cartesianChart1.Series = series;

补充说明:

  • 若你的X轴绑定的是DateTime类型的数值而非字符串标签,无需查找索引,直接将Value赋值为对应8月21日的DateTime实例即可
  • 若Tooltip不触发,可调整cartesianChart1.DataTooltip.InitialDelay属性降低显示延迟,或给标线增加StrokeThickness = 2提升响应面积
  • 若需要限制标线的垂直显示范围,给AxisSection添加FromValue和ToValue属性指定Y轴上下限即可,默认不填会贯穿整个Y轴

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:54:03