我一直坚持这个问题好几个小时......我想要做的事实上很简单 - 在ComboBox中设置默认的选定项目(我使用的是MVVM模式)。
我在视图中为ComboBox提供了以下XAML:
<ComboBox ItemsSource="{Binding Schools}"
DisplayMemberPath="Acronym"
SelectedValue="{Binding SelectedSchool}"
SelectedValuePath="Id"
/>
在我的ViewModel中,我有一个ObservableCollection,Schools:
public ObservableCollection<School> Schools { get; private set; }
public CourseFormViewModel()
{
Schools = new ObservableCollection<School>();
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");
}
}
最后,学校是一个简单的业务对象:
[DataContract]
public class School
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Acronym { get; set; }
[DataMember]
public string Name { get; set; }
}
问题是,当应用程序启动时,组合框不会获得默认值。我已经尝试在XAML中将SelectedIndex设置为0,但无济于事。我已经尝试在代码隐藏(可以工作)中的Window_Loaded事件处理程序中设置SelectedIndex,但是因为我使用的MVVM模式感觉有点脏。我对这整个WPF / MVVM的东西还是新手,所以如果有人能指出我正确的方向,我将不胜感激。
答案 0 :(得分:5)
您可以像这样设置SelectedSchool:
public void CourseFormViewModel()
{
Schools = new ObservableCollection<School>();
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);
而不是分配常数值。