I've been stuck on this problem for hours... what I want to do is actually quite simple - set a default selected item in a ComboBox (I'm using the MVVM pattern).
I have the following XAML for the ComboBox in my View:
<ComboBox ItemsSource="{Binding Schools}"
DisplayMemberPath="Acronym"
SelectedValue="{Binding SelectedSchool}"
SelectedValuePath="Id"
/>
In my ViewModel, I have an 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");
}
}
Finally, School is a simple business object:
[DataContract]
public class School
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Acronym { get; set; }
[DataMember]
public string Name { get; set; }
}
The problem is, that when the application is started, the combobox does not get a default value. I've tried setting the SelectedIndex to 0 in XAML, but to no avail. I've tried setting the SelectedIndex in a Window_Loaded event handler in the code-behind (which works), but since I'm using the MVVM pattern that feels kind of dirty. I'm still new to this whole WPF/MVVM stuff, so if someone could point me in the right direction I would be grateful.
Schools
is of typeSchool
whileSelectedSchool
is of typeint
? May this is your problem? – GameScriptingSelectedSchool
a part of theSchools
collection? If not then you'll have to do more research on your own. – GameScripting