2017-08-01 95 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