我正在尝试实现一个实时绘图 UI,我使用 WPF 和 MVVM 模式和 beto-rodriguez 的实时图表作为我的绘图库,但是我在实时更新图表时遇到了一些麻烦。我知道我必须运行多个线程来实时更新 UI,但是我尝试的每一种方法都不起作用(我现在正在学习 C#)。我很困惑我应该如何正确地实现这个模式以进行实时更新,以及绘图库是否能够做到这一点。
这是我的实际代码(它是我将要做的简化版本并且不实现任何多线程代码)
模型视图代码:
using System;
using System.ComponentModel;
using System.Windows;
using LiveCharts;
namespace TestMotionDetection
{
class MainViewModel : INotifyPropertyChanged
{
public SeriesCollection Series { get; set; }
public Func<double, string> YFormatter { get; set; }
public Func<double, string> XFormatter { get; set; }
public DataViewModel SData
{
set
{
Series[0].Values.Add(value);
OnPropertyChanged("Series");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MainViewModel()
{
SeriesConfiguration<DataViewModel> config = new SeriesConfiguration<DataViewModel>();
config.Y(model => model.Value);
config.X(model => model.Time);
Series = new SeriesCollection(config)
{
new LineSeries {Values = new ChartValues<DataViewModel>(), PointRadius = 0}
};
XFormatter = val => Math.Round(val) + " ms";
YFormatter = val => Math.Round(val) + " °";
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void generateData()
{
DataViewModel val = new DataViewModel();
for (int i = 0; i < 500; i++)
{
val.Time = i;
val.Value = i + 2.3f;
SData = val;
}
}
}
}
这是查看代码:
using System.Windows;
namespace TestMotionDetection
{
/// <summary>
/// Logica di interazione per MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private MainViewModel vista;
public MainWindow()
{
vista = new MainViewModel();
DataContext = vista;
}
private void button_Click(object sender, RoutedEventArgs e)
{
vista.generateData();
}
}
}
和 XALM:
<Window x:Class="TestMotionDetection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="clr-namespace:LiveCharts;assembly=LiveCharts"
Title="Example 2 (WPF)"
Width="1025.213"
Height="482.801">
<Grid>
<lvc:LineChart Margin="0,2,245,-2"
LegendLocation="Right"
Series="{Binding Series}">
<lvc:LineChart.AxisX>
<lvc:Axis LabelFormatter="{Binding XFormatter}" Separator="{x:Static lvc:DefaultAxes.CleanSeparator}" />
</lvc:LineChart.AxisX>
<lvc:LineChart.AxisY>
<lvc:Axis LabelFormatter="{Binding YFormatter}" />
</lvc:LineChart.AxisY>
</lvc:LineChart>
<Button x:Name="button"
Width="151"
Height="79"
Margin="804,47,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="button_Click"
Content="Button" />
</Grid>
</Window>
[更新 1] [ ] 1