在WPF MVVM应用程序中的ComboBox中设置默认选定项

几个小时我一直坚持这个问题……我想做的事实上很简单 – 在ComboBox中设置一个默认的选定项目(我使用的是MVVM模式)。

我在视图中为ComboBox提供了以下XAML:

 

在我的ViewModel中,我有一个ObservableCollection,Schools:

  public ObservableCollection Schools { get; private set; } public CourseFormViewModel() { Schools = new ObservableCollection(); try { // Gets schools from a web service and adds them to the Schools ObservableCollection PopulateSchools(); } catch (Exception ex) { // ... } } public int SelectedSchool { get { return schoolId; } set { schoolId = value; OnPropertyChanged("SelectedSchool"); } } 

最后,School是一个简单的业务对象:

 [DataContract] public class School { [DataMember] public int Id { get; set; } [DataMember] public string Acronym { get; set; } [DataMember] public string Name { get; set; } } 

问题是,当应用程序启动时,combobox不会获得默认值。 我已经尝试在XAML中将SelectedIndex设置为0,但无济于事。 我已经尝试在代码隐藏(可以工作)中的Window_Loaded事件处理程序中设置SelectedIndex,但是因为我正在使用感觉有点脏的MVVM模式。 我仍然是这个WPF / MVVM的新手,所以如果有人能指出我正确的方向,我将不胜感激。

您可以像这样设置SelectedSchool:

 public void CourseFormViewModel() { Schools = new ObservableCollection(); try { // Gets schools from a web service and adds them to the Schools ObservableCollection PopulateSchools(); SelectedSchool = 3; } catch (Exception ex) { // ... } } 

测试数据:

  Schools.Add(new School { Id = 1, Name = "aaa", Acronym = "a" }); Schools.Add(new School { Id = 2, Name = "bbb", Acronym = "b" }); Schools.Add(new School { Id = 3, Name = "ccc", Acronym = "c" }); 

并且您将获得所选项目“c”。

如果你想使用最小的Id的init ComboBox,你可以使用这个代码:

 SelectedSchool = Schools.Min(x => x.Id); 

而不是分配常量值。