更新ObservableCollection而不清除它?

时间:2018-01-22 15:52:25

标签: c# wpf data-binding

我试图使用observablecollection将数据绑定到datagrid,并想知道如何在不清除它的情况下更新集合。 每隔500毫秒提供一次新数据。

目前有什么是我每次都清除Observable集合并使用新数据重新添加项目。 虽然这很好用,但在UI上看不到任何闪烁,但我想知道是否有更新集合的正确方法。

    private ObservableCollection<AC> m_Label = new ObservableCollection<AC>();
    public ObservableCollection<AC> Label
    {
        get => m_Label;
        private set => Set(ref m_Label, value);
    }

    ...
    ...
    ...
    Label = ThreadInvoker.Instance.RunByUiThread(() => {
                Label.Clear();
                return Label; });

    {
        //parse and convert data that is provided every 500 milisecond
        ...
        ...

        Label = ThreadInvoker.Instance.RunByUiThread(() => {
                Label.Add(new AC(pass parameters obtained from the new data);
                return Label; });
        }
    }

XAML

  <StackPanel Grid.Column="2">
            <Label Content="Customer"/>
            <DataGrid ItemsSource="{Binding Path=Label}"  Name="dgCustomer" AutoGenerateColumns="False"  IsReadOnly="True">
                <DataGrid.Columns>
                    <DataGridTextColumn Width="Auto" Header="ID" Binding="{Binding AlcoveId}"/>
                    <DataGridTextColumn Width="Auto" Header="Description" Binding="{Binding StateDescription}"/>
                    <DataGridTextColumn Width="Auto" Header="OrderID" Binding="{Binding OrderID}"/>
                </DataGrid.Columns>
            </DataGrid>
   </StackPanel>

1 个答案:

答案 0 :(得分:1)

由于集合不会改变,你可能更好的只是更新单个类;例如:

class MyData : INotifyPropertyChanged
{
    public decimal StockPrice {get;set;} // ToDo: Call notify property changed
}

. . .

ObservableCollection<MyData> Data;

. . .

foreach (var d in Data)
{
    d.StockPrice = Rnd.Next(...);
}