WPF圖表Live Charts(一)基礎
Live Chart一個開源的項目,控件使用簡單,有充足的實列和豐富的文檔資料。同時界面也比較美觀,可定製性也很高。官網地址:https://lvcharts.net。
官網有詳細的介紹和豐富的實例,大家可以自行查看。本人主要介紹一下官網的教程同時補充說明一下官方教程沒有說明的一些地方。
安裝Live Charts的庫
右鍵單擊項目的引用節點,然後選擇“Manage NuGet Packages”,然後搜索Live Charts,安裝即可。
添加Live Charts名稱空間
XAML引用名稱空間
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
後臺代碼引用名稱空間
using LiveCharts;
using LiveCharts.Wpf;
窗口界面添加圖表控件
<lvc:CartesianChart Series="{Binding SeriesCollection}" />
將上面代碼塊放到Gaid等容器控件內,就添加了Live Chart控件。其中CartesianChart爲圖表控件,通過Binding進行數據綁定。
後臺代碼
首先聲明屬性SeriesCollection
public SeriesCollection SeriesCollection { get; set; }
添加曲線和數據
SeriesCollection = new SeriesCollection
{
new LineSeries
{
Values = new ChartValues<double> { 3, 5, 7, 4 }
},
new ColumnSeries
{
Values = new ChartValues<decimal> { 5, 6, 2, 7 }
}
};
LineSeries爲折線圖,ColumnSeries爲柱狀圖。
綁定數據
DataContext = this;
通過DataContext綁定XAML的數據。
完整代碼如下
<Window x:Class="chart_line.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:chart_line"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<lvc:CartesianChart Series="{Binding SeriesCollection}" />
</Grid>
</Window>
using LiveCharts;
using LiveCharts.Wpf;
namespace chart_line
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public SeriesCollection SeriesCollection { get; set; }
public MainWindow()
{
InitializeComponent();
SeriesCollection = new SeriesCollection
{
new LineSeries
{
Values = new ChartValues<double> { 3, 5, 7, 4 }
},
new ColumnSeries
{
Values = new ChartValues<decimal> { 5, 6, 2, 7 }
}
};
DataContext = this;
}
}
}
運行如圖
一組折線圖,一組柱狀圖。