[英]C# Displaying String of ObservableCollection on event CollectionChanged
[英]c# mvvm nested ObservableCollection CollectionChanged NewStartingIndex >0
我是stackoverflow的新手。 我一整天都在尋找解決方案所以我決定在這里問一下。
我正在開發一個使用WPF和數據綁定/ MVVM的應用程序。 我有一個嵌套的ObservableCollection,它是Class Program的一部分。 兩者都正確實現了INotifyPropertyChange。
在我的構造函數中,我創建了一個名為ListPrograms的Program類型的ObservableColletion,並使用程序列表從我的數據服務中填充它。 這很好用。 此外,綁定工作正常,在我的主視圖中,我選擇了一個程序,並且詳細視圖中顯示了嵌套的價格列表。 OnPropertyChange正確觸發SalesPrice的每個屬性。
我的要求是,在用戶輸入時,程序需要重新計算嵌套列表的每個行項目中的累積價格。 我有一個正確執行此操作的方法。
我命令運行該方法,我試圖附加一個collectionchanged事件。
`void GetPrograms()
{
ListPrograms.Clear();
var prgms = DataService.GetProgramList(SearchStringProgram);
ListPrograms=new ObservableCollection<Program>(prgms);
foreach (var prg in ListPrograms)
{
prg.SalesPrices.CollectionChanged+=SalesPrices_CollectionChanged;
} `
///
void SalesPrices_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (SalesPrice item in e.NewItems)
item.PropertyChanged += SalePrice_PropertyChanged;
if (e.OldItems != null)
foreach (SalesPrice item in e.OldItems)
item.PropertyChanged -= SalePrice_PropertyChanged;
}
void SalePrice_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
RecalcSalePrice(CurrentProgram.SalesPrices);
}
我遇到的問題是集合更改事件僅在我在運行時添加到集合的新SalesPrices中注冊。 我查看了e.NewStartingIndex,它以初始SalesPrice記錄的數量開頭。 (例如,第一個程序和9個銷售價格,它的ObservableColletion和e.NewStartingIndex的值為8)。 當我在運行時將新記錄添加到列表中時,偶數正在注冊並通知更改。
我認為這種情況正在發生,因為我從dataservice傳遞了Program對象,其中包含SalesPrices的填充列表,並且該事件僅注冊新項目。
任何想法?
坦率
只需在首次解析時為所有現有集合項執行事件訂閱:
void GetPrograms()
{
var prgms = DataService.GetProgramList(SearchStringProgram);
ListPrograms=new ObservableCollection<Program>(prgms);
foreach (var prg in ListPrograms)
{
prg.SalesPrices.CollectionChanged += SalesPrices_CollectionChanged;
foreach (SalesPrice item in prg.SalesPrices)
{
item.PropertyChanged += SalePrice_PropertyChanged;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.