如何更改ObservableCollection中的数据

时间:2016-08-01 09:18:07

标签: c# wpf add observablecollection clear

如果不在我的收藏中添加或使用add,我如何更改ObservableCollection中的数据?

var items = await service.GetTrucksAsync();
foreach (var item in items)
{
    MyCollection.Add(new TruckItems
    {
        TruckId = item.TruckId,
        TruckQuoteId = item.QuoteId,
        TruckPhaseId = item.CurrentPhaseId,
        TruckChassisManufacturer = item.ChassisManufacturer,
        TruckChassisModel = item.ChassisModel,
        TruckStatus = item.Status,
        TruckJobNumber = item.JobNumbers,
        TruckAddedBy = item.AddedBy,
        TruckClientName = item.ClientName,
        TruckClientSurname = item.ClientSurname,
        TruckClientDetail = item.ClientDetail,
        TruckCurrentPhase = item.CurrentPhase
    });
}
dgViewProjects.ItemsSource = MyCollection;

我不想再次清除集合和添加数据,因为它会导致我的数据网格的用户界面闪烁' (再次清除并加载新数据)。我需要它像地狱般平稳。 :)

编辑:INotifyPropertyChanged在我的课程中实现

public class TruckItems : INotifyPropertyChanged
{
    ...
    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }        
}

1 个答案:

答案 0 :(得分:1)

TruckItems类需要实现INotifyPropertyChanged接口。

例如:

public class TruckItems : INotifyPropertyChanged
{
    private int _truckQuoteId;

    public int TruckQuoteId
    {
        get { return _truckQuoteId; }
        set
        {
            if(value != _truckQuoteId)
            {
                value = _truckQuoteId;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TruckQuoteId));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

如果您无法更改TruckItems类(DAL),则需要创建新类并复制属性。 (例如使用Mapper

更新

您遇到的问题是,您正在创建TruckItems的新实例。

var items = await service.GetTrucksAsync();
foreach (var item in items)
{
    var truckItem = MyCollection.FirstOrDefault(i => i.TruckId == item.TruckId);

    bool isNew = false;

    if(truckItem == null)
    {
        truckItem = new TruckItems();
        isNew = true;
    }

    truckItem.TruckId = item.TruckId;
    truckItem.TruckQuoteId = item.QuoteId;
    truckItem.TruckPhaseId = item.CurrentPhaseId;
    truckItem.TruckChassisManufacturer = item.ChassisManufacturer;
    truckItem.TruckChassisModel = item.ChassisModel;
    truckItem.TruckStatus = item.Status;
    truckItem.TruckJobNumber = item.JobNumbers;
    truckItem.TruckAddedBy = item.AddedBy;
    truckItem.TruckClientName = item.ClientName;
    truckItem.TruckClientSurname = item.ClientSurname;
    truckItem.TruckClientDetail = item.ClientDetail;
    truckItem.TruckCurrentPhase = item.CurrentPhase;

    if(isNew )
       MyCollection.Add(truckItem);

}