我正在使用一个名为LiveCharts的库。我的目标是显示动态数据与时间的图表(例如,我拥有的金额)。我已经看过教程和示例;但是,我不明白如何自动绑定我的数据!
是否可以使用 LiveCharts 从 .NET ObservableCollection中的数据创建动态图表,以便图表在集合中的数据发生变化时发生变化?
我正在使用一个名为LiveCharts的库。我的目标是显示动态数据与时间的图表(例如,我拥有的金额)。我已经看过教程和示例;但是,我不明白如何自动绑定我的数据!
是否可以使用 LiveCharts 从 .NET ObservableCollection中的数据创建动态图表,以便图表在集合中的数据发生变化时发生变化?
在我看来,您不需要ObservableCollection
因为LiveCharts.ChartValues
已经可以观察到,并且会在添加项目时通知。
在此示例中,您可以看到当RandomizeChartCommand
调用 时,图表将由于其绑定而自动更改。
包.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CommonServiceLocator" version="2.0.4" targetFramework="net471" />
<package id="LiveCharts" version="0.9.7" targetFramework="net471" />
<package id="LiveCharts.Wpf" version="0.9.7" targetFramework="net471" />
<package id="MvvmLightLibs" version="5.4.1" targetFramework="net471" />
</packages>
ViewModel(我安装了 NuGet 库MvvmLightLibs
来获取RelayCommand
实现):
public class TestViewModel
{
public SeriesCollection ChartData { get; }
private readonly ChartValues<double> _ys;
public ICommand RandomizeChartCommand { get; }
private static Random _random;
public TestViewModel()
{
RandomizeChartCommand = new RelayCommand(RandomizeChart);
_random = new Random();
_ys = new ChartValues<double>();
ChartData = new SeriesCollection()
{
new LineSeries() { Values = _ys }
};
}
public void RandomizeChart()
{
_ys.Clear();
for (int i = 0; i < 100; ++i)
{
_ys.Add(_random.NextDouble() * 100);
}
}
}
主窗口.xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
Title="Test chart" Height="450" Width="800">
<DockPanel LastChildFill="True">
<StackPanel DockPanel.Dock="Bottom" Margin="10" >
<Button Content="Randomize" HorizontalAlignment="Center" Padding="20, 10" Command="{Binding RandomizeChartCommand}" />
</StackPanel>
<lvc:CartesianChart Series="{Binding ChartData}" />
</DockPanel>
</Window>
如您尝试此示例所见,当您编辑_ys
集合(添加或删除元素)时,图表将更新。