2015-04-06 84 views
1

当过我添加新项ObservableCollectionCollectionChanged事件可以正常使用,的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事件不工作复制的项目。

我该如何解决这个问题?

+0

,你实际注册为BOM_CollectionChanged地方?我没有看到它,但你显然没有包含代码的工具部分。 –

+0

为什么所有的注册。在BOMForDesignMasterModel Weight集合中,只需调用NotifyPropertyChanged(“TotalWeight”);并得到它计算总重量。 – Paparazzi

+1

@SamAlex不知道我理解你的问题,但当你创建列表时,它不会为你在构造函数中传递的项目引发'CollectionChanged'事件,因为a)它不需要b)没有'CollectionChanged'事件处理程序尚未分配。基本上在'BOM'属性的setter中,在您指定'CollectionChanged'处理程序的位置,列表已经完全创建并且包含初始项目 – dkozl

回答

0

我觉得这是你的问题:

BOM = new ObservableCollection<BOMForDesignMasterModel>(BOMCollection.Where(x => x.DesignMasterId == value.DesignMasterId)); 

当你新的这个样子你不改变其内容,这将火NotifyPropertyChanged一个ObservableCollection。您正在更改ObservableCollection的实例,而不是。

尽管您不能只是新建ObservableCollection,但您可以使用“清除/添加/删除”来根据需要更改其内容。为了防止你的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); 
     } 
    } 
} 
相关问题