我异步获取数据并尝试通过 LineSeries 填充绘图,但更新绑定集合(ObservableCollection)时绘图不会刷新。注意:当绑定集合更改时,我有一个调用 InvalidatePlot(true) 的 XAML 行为。
谁能解释为什么情节没有按预期更新?
WPF .Net 4.0 OxyPlot 2014.1.293.1
我有以下 XAML 数据模板,您可以看到 LineSeries ItemsSource 绑定到 ViewModel 中的属性 (PlotData):
<DataTemplate DataType="{x:Type md:DataViewModel}">
<Grid>
<oxy:Plot x:Name="MarketDatePlot"
Margin="10">
<oxy:Plot.Axes>
<oxy:DateTimeAxis Position="Bottom"
StringFormat="dd/MM/yy"
MajorGridlineStyle="Solid"
MinorGridlineStyle="Dot"
IntervalType="Days"
IntervalLength="80" />
<oxy:LinearAxis Position="Left"
MajorGridlineStyle="Solid"
MinorGridlineStyle="Dot"
IntervalLength="100" />
</oxy:Plot.Axes>
<oxy:LineSeries ItemsSource="{Binding Path=PlotData, Mode=OneWay}" />
<i:Interaction.Behaviors>
<behaviors:OxyPlotBehavior ItemsSource="{Binding Path=PlotData, Mode=OneWay}" />
</i:Interaction.Behaviors>
</oxy:Plot>
</Grid>
</DataTemplate>
正如我所说,ViewModel 请求并异步填充绑定集合(绑定集合的实际填充发生在 UI 线程上):
public sealed class DataViewModel : BaseViewModel, IDataViewModel
{
private readonly CompositeDisposable _disposable;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly RangeObservableCollection<DataPoint> _plotData;
public DataViewModel(DateTime fromDate, DateTime toDate, IMarketDataService marketDataService, ISchedulerService schedulerService)
{
_plotData = new RangeObservableCollection<DataPoint>();
_disposable = new CompositeDisposable();
if (fromDate == toDate)
{
// nothing to do...
return;
}
_cancellationTokenSource = new CancellationTokenSource();
_disposable.Add(Disposable.Create(() =>
{
if (!_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
}
}));
marketDataService.GetDataAsync(fromDate, toDate)
.ContinueWith(t =>
{
if (t.IsFaulted)
{
throw new Exception("Failed to get market data!", TaskHelper.GetFirstException(t));
}
return t.Result.Select(x => new DataPoint(DateTimeAxis.ToDouble(x.Time), x.Value));
}, schedulerService.Task.Default)
.SafeContinueWith(t => _plotData.AddRange(t.Result), schedulerService.Task.CurrentSynchronizationContext);
}
public void Dispose()
{
_disposable.Dispose();
}
public IEnumerable<DataPoint> PlotData
{
get { return _plotData; }
}
}
XAML 行为如下所示:
(我似乎无法粘贴更多代码,所以在保存时不断抛出错误)