我在ObservableCollection
CollectionChanged
事件中添加新项目时效果非常好,
这是 MVVM代码
public List<BOMForDesignMasterModel> BOMCollection { get; set; }
public ObservableCollection<BOMForDesignMasterModel> BOM
{
get { return _BOM; }
set
{
_BOM = value;
NotifyPropertyChanged("BOM");
BOM.CollectionChanged += BOM_CollectionChanged;
}
}
public DesignMasterModel DesignMaster
{
get
{
return _DesignMaster;
}
set
{
if (value != null)
{
_DesignMaster = value;
BOM.Clear();
BOM = new ObservableCollection<BOMForDesignMasterModel>(BOMCollection.Where(x => x.DesignMasterId == value.DesignMasterId));
NotifyPropertyChanged("DesignMaster");
}
}
}
void BOM_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (BOMForDesignMasterModel item in e.NewItems)
item.PropertyChanged += item_PropertyChanged;
if (e.OldItems != null)
foreach (BOMForDesignMasterModel item in e.OldItems)
item.PropertyChanged -= item_PropertyChanged;
}
public String TotalWeight { get { return _TotalWeight; } set { _TotalWeight = value; NotifyPropertyChanged("TotalWeight"); } }
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Weight")
{
TotalWeight = BOM.Sum(x => x.Weight).ToString();
}
}
这里使用基于条件的副本集合,
BOM = new ObservableCollection<BOMForDesignMasterModel>(BOMCollection.Where(x => x.DesignMasterId == value.DesignMasterId));
当我确实喜欢这个item_PropertyChanged事件时,无法处理复制的项目。
如何解决此问题?
答案 0 :(得分:0)
我认为这是你的问题:
BOM = new ObservableCollection<BOMForDesignMasterModel>(BOMCollection.Where(x => x.DesignMasterId == value.DesignMasterId));
当您新建这样的ObservableCollection时,您不会更改其内容,这将触发NotifyPropertyChanged。您正在更改ObservableCollection的实例,而不是。
虽然您不能只是新建ObservableCollection,但可以使用Clear / Add / Remove来根据需要更改其内容。为了防止你的setter变得太乱,我建议将这个逻辑移到自己的方法中,并找到一些其他方法来触发它。
这看起来像这样:
private void RefreshBOM(int designMasterId)
{
BOM.Clear();
var bomResult = BOMCollection.Where(x => x.DesignMasterId == designMasterId);
if(bomResult != null)
{
foreach(var result in bomResult)
{
BOM.Add(result);
}
}
}