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