C# – Setting a default selected item in ComboBox in WPF MVVM application

ccomboboxmvvmwpf

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.

Best Answer

You can set SelectedSchool like this:

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)
        {
            // ...
        }
    }

Test data:

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

And you will get selected item "c".

If you want init ComboBox with the smallest Id you can use this code:

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

Instead of assign constant value.

Related Topic