I'm writing a DB management app in c# using uwp and mvvm-light and I can't display a default selectedValue in my combobox without opening it and manually selecting one first.
Here is my view :
<ComboBox x:Name="editCategory" Header="Category" ItemsSource="{Binding Categories}" SelectedValue="{Binding CategoryCode, Mode=TwoWay}" SelectedValuePath="Code" DisplayMemberPath="Name"/>
Here's my ViewModel :
private ObservableCollection<Category> _categories;
public ObservableCollection<Category> Categories {
get { return _categories; }
set {
if (_categories == value)
return;
_categories = value;
RaisePropertyChanged("Categories");
}
}
private int _categoryCode;
public int CategoryCode {
get { return _categoryCode; }
set {
if (_categoryCode == value)
return;
_categoryCode = value;
RaisePropertyChanged("CategoryCode");
}
}
And my model :
class Category
{
public int Code { get; set; }
[Required]
public string Name { get; set; }
}
I can display the different values when opening the combobox, when I select a value, it displays it correctly when the combobox is closed.
I know the binding is working because if I set a breakpoint in the setter of CategoryCode in my ViewModel, it shows the correct updated value.
The problem is that when I load the page, the default value is not selected when it should display the Category.Name of the item where Category.Code = CategoryCode
Please help me if you can, I've been searching for hours, and nothing I could find has helped me so far
I believe you need to set your SelectedItem
or SelectedValue
to the correct loaded variable before the form/control is loaded.