1
votes

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.

1
Schools is of type School while SelectedSchool is of type int? May this is your problem?GameScripting
Hmm, I changed the SelectedSchool property to return School instead of int, but it didn't make any difference. Do I have to change anything else?William
hm, the only thing that might be wrong ... is SelectedSchool a part of the Schools collection? If not then you'll have to do more research on your own.GameScripting

1 Answers

5
votes

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.