[英]Realtime UI and LiveCharts update in MVVM
我正在嘗試實現一個實時繪圖 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
你的 XFormatter 和 YFormatter 都應該是這樣的:
private Func<double, string> _yFormatter;
public Func<double, string> YFormatter {
get{ return _yFormatter; }
set
{
_yFormatter = value;
OnPropertyChanged("YFormatter");
}
如果您使用的是 C#6,則應nameof(YFormatter)
使用nameof(YFormatter)
。
這將導致視圖更新,否則視圖無法知道格式化程序已更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.