1
当过我添加新项ObservableCollection
CollectionChanged
事件可以正常使用,的ObservableCollection CollectionChanged事件problum
这里是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事件不工作复制的项目。
我该如何解决这个问题?
,你实际注册为BOM_CollectionChanged地方?我没有看到它,但你显然没有包含代码的工具部分。 –
为什么所有的注册。在BOMForDesignMasterModel Weight集合中,只需调用NotifyPropertyChanged(“TotalWeight”);并得到它计算总重量。 – Paparazzi
@SamAlex不知道我理解你的问题,但当你创建列表时,它不会为你在构造函数中传递的项目引发'CollectionChanged'事件,因为a)它不需要b)没有'CollectionChanged'事件处理程序尚未分配。基本上在'BOM'属性的setter中,在您指定'CollectionChanged'处理程序的位置,列表已经完全创建并且包含初始项目 – dkozl