Silverlight 4 Combobox with selectedValue using MVVM-Light

北城余情 提交于 2019-12-11 23:09:49

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/3554174/silverlight-4-combobox-with-selectedvalue-using-mvvm-light

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!