Solution for WPF Combo Box binding with a object type value
I found that the ComboBox WPF binding in WPF does not work correctly if the binding value is of an object type. Even when I set SelectedValuePath="Id", the binding fails to set the value. When a different value in the ComboBox is selected, the new selected value should be set in the ViewModel too. However, this does not happen this way.
I got a solution for this issue, which is to set the SelectedValue to be the CategoryId:
<ComboBox Grid.Row="3" Grid.Column="1" ItemsSource="{Binding CategoryList}" DisplayMemberPath="Name" SelectedItem="CategoryId" SelectedValue="{Binding CategoryId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Id" Margin="5"/>
Inside the ViewModel:
public int CategoryId { get => _selectedCategoryId; set { if (_selectedCategoryId != value) { //_selectedCategory = value; _item.CategoryId = value; _item.Category = CategoryList.FirstOrDefault(c => c.Id == value); OnPropertyChanged(); } } }
Then it will work!
Trackback address for this post
Trackback URL (right click and copy shortcut/link location)
Feedback awaiting moderation
This post has 527 feedbacks awaiting moderation...
Form is loading...