簡體   English   中英

ObservableCollection CollectionChanged事件概率

[英]ObservableCollection CollectionChanged event problum

每當我向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事件無法復制項目時。

如何解決此問題?

我認為這是您的問題:

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

當您像這樣新建一個ObservableCollection時,您不會更改其內容 ,這將觸發NotifyPropertyChanged。 您正在更改ObservableCollection的實例 ,但沒有更改。

雖然不能只是對ObservableCollection進行新的更新,但可以根據需要使用Clear / Add / Remove更改其內容。 為了防止設置程序過於混亂,我建議將邏輯移到自己的方法中,並找到其他觸發它的方法。

看起來像這樣:

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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM