views:

181

answers:

1

I have recently started using the MVVM-Light toolkit and I am stuck on the following problem: I have a basic Silverlight Combobox that is bound to a viewmodel with an ObservableCollection of type MyUser. The Combobox implements a custom DataTemplate to combine the user’s name and surname. After loading the list of users, how do I set the Combobox to select the first user in the list and display this selected user in the collapsed Combobox? I know that it has been suggested to use the SelectedValue property but I have not been able to get it to work using either SelectedItem or SelectedValue. Put another way, even though I set the SelectedValue/SelectedItem after the list of users has been loaded the selected MyUser does not display as selected in the combobox, how do I achieve this? Please see the XAML below:

<ComboBox
    ItemsSource="{Binding MyUsers, Mode=OneWay}"
    SelectedItem="{Binding SelectedUser, Mode=TwoWay}"
    IsEnabled="{Binding IsReady}">
       <ComboBox.ItemTemplate>
           <DataTemplate>
               <StackPanel Orientation="Horizontal">
                  <TextBlock Text="{Binding Name}"></TextBlock>
                  <TextBlock Text=" "></TextBlock>
                  <TextBlock Text="{Binding Surname}"></TextBlock>
               </StackPanel>
           </DataTemplate>
       </ComboBox.ItemTemplate>
 </ComboBox>

The View Model Code is as follows:

public ObservableCollection<MyUser> MyUsers
{
    get
    {
        return myUsers;
    }
    set
    {
        if (myUsers == value)
        {
            return;
        }
        myUsers = value;
        SelectedUser = myUsers.FirstOrDefault();
        IsReady = true;
        RaisePropertyChanged("MyUsers");
    }
}

public MyUser SelectedUser
{
    get
    {
        return selectedUser;
    }
    set
    {
        if (selectedUser == value)
        {
            return;
        }
        selectedUser = value;
        RaisePropertyChanged("SelectedUser");
    }
}
A: 

The answer is simple, you have to raise the PropertyChanged event for the List of MyUsers before setting the Selected User in the viewModel, i.e. notify the UI that the ItemsSource has changed before updating the SelectedValue.