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