从不同的线程向数据绑定Polyline PointCollection添加Point

时间:2017-10-06 13:40:09

标签: c# wpf mvvm polyline

我有这个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不会更新。我有什么遗失的吗?

0 个答案:

没有答案