In XAML I have a combobox defined as:
<ComboBox x:Name="UsernameComboBox"
ItemsSource="{Binding Users}"
DisplayMemberPath="Username"
SelectedItem="{Binding Path=SelectedName, Mode=TwoWay}"/>
Right now, it doesn’t show any default selected item.
I fill the combo box with a list:
public List<User> Users
{
get
{
return _userRepository.RetrieveUsers();
}
}
public List<User> RetrieveUsers()
{
_users = (from Users in _db.Users select Users).ToList();
return _users;
}
The proper Users being the ItemSource for the combobox. then in the XAML I defined SelectedItem and bound it to a property called Selected name.
In code this looks like:
private User _selectedName;
public User SelectedName
{
get
{
return _selectedName;
}
set
{
if (_selectedName == value) return;
_selectedName = value;
OnPropertyChanged("SelectedName");
}
}
How can I get my combobox to show a selectedItem at startup?
One problem I can see is that each time
Usersproperty is accessed, theRetrieveUsers()method is invoked which re-runs your database query. This is going to upset yourSelectedItembinding which will expect the list of items bound to theComboBoxto be unchanged. In other words, it finds the selected item by evaluating the equality of theSelectedItemagainst the collection of bound items.You need to query the database once …
This will also ensure that the first item is selected.