C# WPF LiveCharts LineSeries X轴日期添加文本:示例教程
要在C# WPF LiveCharts的LineSeries上添加一个文本,在图表上方显示日期,可以使用Annotations属性。
以下是一个示例代码:
using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using System;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 创建一个LineSeries
var lineSeries = new LineSeries
{
Title = 'Series 1',
Values = new ChartValues<ObservablePoint>
{
new ObservablePoint(0, 3),
new ObservablePoint(1, 4),
new ObservablePoint(2, 6),
new ObservablePoint(3, 8),
new ObservablePoint(4, 7),
new ObservablePoint(5, 5),
new ObservablePoint(6, 6)
}
};
// 创建一个Annotations
var textAnnotation = new TextAnnotation
{
Text = DateTime.Now.ToShortDateString(),
X = 3,
Y = 8,
Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red),
FontWeight = FontWeights.Bold
};
// 创建一个Chart
var chart = new CartesianChart
{
Series = new SeriesCollection { lineSeries },
Annotations = new AnnotationsCollection { textAnnotation },
AxisX = new Axis
{
Title = 'X Axis',
Labels = new[] { '0', '1', '2', '3', '4', '5', '6' },
Separator = new Separator { Step = 1 }
},
AxisY = new Axis
{
Title = 'Y Axis',
LabelFormatter = value => value.ToString(),
Separator = new Separator { Step = 1 }
}
};
// 添加Chart到Grid中
ChartGrid.Children.Add(chart);
}
}
}
在这个示例中,我们创建了一个LineSeries并添加了一些数据点。然后,我们创建了一个TextAnnotation并设置了它的文本、位置、边框颜色和字体加粗。最后,我们创建了一个CartesianChart并将LineSeries和TextAnnotation添加到它的Series和Annotations集合中,并将其添加到Grid中显示。
请注意,示例中的ChartGrid是一个在XAML中定义的Grid,用于放置Chart。确保在XAML中正确定义了ChartGrid。
希望这可以帮助到你!
原文地址: https://www.cveoy.top/t/topic/o5wl 著作权归作者所有。请勿转载和采集!