将ComboBoxes itemssource与Dictionary绑定

时间:2017-08-01 22:17:24

标签: c# wpf combobox

为什么第一个例子不会更新comboBoxes itemsSource,但第二个会更新?据我所知,如果我明确调用OnPropertyChanged(),它会通知GUI并从我的VM获取新值。

示例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 - 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();

        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);

1 个答案:

答案 0 :(得分:1)

在向字典添加/删除项目时,不会创建任何属性更改通知。但是,当您重新分配属性时,它会触发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/