我尝试使用 MVVM 模式制作一个简单的 WPF 应用程序。它有一个文本框、一个文本块和一个 Oxyplot 图视图。 ** ViewModel 类**
public class ViewModel : INotifyPropertyChanged
{
private PlotModel? plotModel;
public PlotModel? PlotModel
{
get => plotModel;
set { plotModel = value; OnPropertyChanged("PlotModel"); }
}
public LineSeries lineSeries { get; set; }
private ObservableCollection<DataPoint>? _BestFitness;
public ObservableCollection<DataPoint>? BestFitness
{
get => _BestFitness;
set { _BestFitness = value; OnPropertyChanged(nameof(BestFitness)); }
}
public ViewModel()
{
PlotModel = new PlotModel();
plot_curve();
}
private double _finish;
public double Finish
{
get => _finish;
set {
_finish = value;
OnPropertyChanged("Finish");
OnPropertyChanged("PlotModel");
PlotModel?.InvalidatePlot(true);
}
}
public void plot_curve() {
Model model = new();
PlotModel?.Series.Clear();
lineSeries = new();
MessageBox.Show(Finish.ToString());
BestFitness = new();
for (double x = 0.0; x <= 5.0; x += 0.1)
BestFitness.Add(new DataPoint(x, model.curve(x, 2)));
BestFitness.Add(new DataPoint(5.1, model.curve(Finish, 2)));
lineSeries.ItemsSource = BestFitness;
PlotModel?.Series.Add(lineSeries);
PlotModel?.InvalidatePlot(true);
}
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
XAML
<oxy:PlotView
BorderBrush="Black"
x:Name="Plot1"
Model="{Binding PlotModel}"
Margin="10,10,10,90"
BorderThickness="1,1,1,1"
Opacity="1.0"
Grid.ColumnSpan="3"
FontSize="14"
Grid.Column="3">
</oxy:PlotView>
<TextBox Grid.Column="2" HorizontalAlignment="Left" Margin="10,57,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"
Text="{Binding Finish, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBlock Grid.Column="2" HorizontalAlignment="Left" Margin="10,77,0,0" Text="{Binding Finish}"/>
我尝试通过添加名为“完成”的点来刷新图表。使用文本框输入“完成”。我使用 INotifyPropertyChanged、ObservableCollection、InvalidatePlot(true),但它不起作用。 textBox-textBlock 绑定工作正常,我可以在 textBlock 中看到 Finish 值。我在刷新图表的代码中缺少什么?
如果当 Finsih 点发生变化时 dataPoint 应该更新,那么你必须更改集合:
private double _finish;
public double Finish
{
get => _finish;
set
{
_finish = value;
BestFitness.RemoveAt(BestFitness.Count - 1);
BestFitness.Add(new DataPoint(5.1, model.curve(_finish, 2)));
OnPropertyChanged("Finish");
OnPropertyChanged("PlotModel");
PlotModel?.InvalidatePlot(true);
}
}