C# 使用字典绑定组合框itemssource

C# 使用字典绑定组合框itemssource,c#,wpf,combobox,C#,Wpf,Combobox,为什么第一个示例不更新ComboBox itemsSource,而第二个示例会更新?据我所知,如果显式调用OnPropertyChanged(),那么它将通知GUI并从我的VM获取新值 示例1-不在GUI中更新(cbo中没有项目) //这是它绑定到的属性 this.AvailableSleepTimes=新字典(); //获取包含值的字典 Dictionary allTimes=RememberTimes管理器.GetRememberTimes(); foreach(始终为KeyValuePai

为什么第一个示例不更新ComboBox itemsSource,而第二个示例会更新?据我所知,如果显式调用OnPropertyChanged(),那么它将通知GUI并从我的VM获取新值

示例1-不在GUI中更新(cbo中没有项目)

//这是它绑定到的属性
this.AvailableSleepTimes=新字典();
//获取包含值的字典
Dictionary allTimes=RememberTimes管理器.GetRememberTimes();
foreach(始终为KeyValuePair对)
{
//添加到字典的逻辑
this.AvailableSleepTimes.Add(pair.Key,pair.Value);
}
OnPropertyChanged(()=>this.AvailableSleepTimes);
示例2-GUI中的更新(cbo已填充)

//这是它绑定到的属性
this.AvailableSleepTimes=新字典();
//获取包含值的字典
Dictionary allTimes=RememberTimes管理器.GetRememberTimes();
Dictionary newList=新字典();
foreach(始终为KeyValuePair对)
{
//添加到字典的逻辑
添加(pair.Key,pair.Value);
}
this.AvailableSleepTimes=newList;
OnPropertyChanged(()=>this.AvailableSleepTimes);

在字典中添加/删除项目时,不会创建属性更改通知。但是,当您重新分配属性时,它会触发OnPropertyChanged并更新GUI

为了在集合添加到时更新GUI,您需要使用ObservableCollection类


请注意,OP显式触发PropertyChanged事件。UI不更新的原因是实际字典实例没有更改,因此绑定目标会忽略更改通知。除此之外,您还可以在internet上找到可观察的医疗实施。
        // 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);
        // 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);