2017-08-01 50 views
0

爲什麼第一個示例不更新comboBoxes itemsSource,但第二個示例會如何?據我所知,如果我明確地調用OnPropertyChanged(),那麼它會通知GUI並從我的虛擬機中獲取新值。用字典綁定ComboBoxes itemssource

例如1 - 在GUI不更新(在CBO沒有任何項目)

 // this is the property it's bound to 
     this.AvailableSleepTimes = new Dictionary<string, int>(); 

     // gets a dictionary with values 
     Dictionary<string, int> allTimes = ReminderTimesManager.GetReminderTimes(); 

     foreach(KeyValuePair<string,int> pair in allTimes) 
     { 
      // logic for adding to the dictionary 
      this.AvailableSleepTimes.Add(pair.Key, pair.Value); 

     } 
     OnPropertyChanged(() => this.AvailableSleepTimes); 

例如2 - 更新的圖形用戶界面(CBO充滿)

 // this is the property it's bound to 
     this.AvailableSleepTimes = new Dictionary<string, int>(); 

     // gets a dictionary with values 
     Dictionary<string, int> allTimes = ReminderTimesManager.GetReminderTimes(); 

     Dictionary<string, int> newList = new Dictionary<string, int>(); 

     foreach(KeyValuePair<string,int> pair in allTimes) 
     { 
      // logic for adding to the dictionary 
      newList.Add(pair.Key, pair.Value); 

     } 
     this.AvailableSleepTimes = newList; 
     OnPropertyChanged(() => this.AvailableSleepTimes); 

回答

0

沒有改變性質創建的通知當你添加/刪除一個項目到字典。但是,當您重新分配屬性時,它會觸發OnPropertyChanged並更新GUI。

爲了使GUI集合時被添加到更新,您需要使用的ObservableCollection類 https://msdn.microsoft.com/en-us/library/ms668604(v=vs.110).aspx

http://www.c-sharpcorner.com/UploadFile/e06010/observablecollection-in-wpf/

+0

注意OP明確觸發一個PropertyChanged事件。 UI不更新的原因是實際的字典實例沒有更改,因此Binding目標會忽略更改通知。除此之外,您還可以在Internet上找到ObservableDictionary實現。 – Clemens