我有这个XAML:
<ItemsControl ItemsSource="{Binding Path=Graphs}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="FrameworkElement.DataContext" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Background="DarkGray">
<Polyline Points="{Binding Path=SignalPoints}" Stroke="{Binding Path=GraphConfiguration.ForegroundColor}" StrokeThickness="1" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
其中Graphs是GraphViewModel的ObservableCollection。 GraphViewModel实现如下:
public class GraphViewModel : INotifyPropertyChanged
{
private PointCollection signalPoints;
public PointCollection SignalPoints
{
get => signalPoints ?? (signalPoints = new PointCollection()); //TODO: capacity for optimization
set
{
if (Equals(value, signalPoints)) return;
signalPoints = value;
OnPropertyChanged(nameof(SignalPoints));
}
}
public void AddData(int data)
{
Application.Current.Dispatcher.Invoke(() =>
{
this.SignalPoints.Add(new Point(this.SignalPoints.LastOrDefault().X + 1, data));
}, DispatcherPriority.Render);
OnPropertyChanged(nameof(SignalPoints));
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
当我从另一个线程使用AddData(int)时,Polyline不会更新。我有什么遗失的吗?