Wpf combobox selected item not working

combobox, selecteditem, wpf

Solution

This is because the reference of `RoleDTO` that your `UserDTO` has, does not match any of the `RoleDTOs` in `Roles` collection which you set as `ItemsSource` of `ComboBox`.

Better define a property on your ViewModel like

    public RoleDTO SelectedRole
    {
        get { return Roles.FirstOrDefault(role => role.Role == User.RoleDto.Role); }
        set { User.RoleDto = value; OnPropertyChanged("SelectedRole"); }
    }

and set it as SelectedItem of you combobox

ItemsSource="{Binding Roles}" SelectedItem="{Binding SelectedRole, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Description" />

Problem

I have two object: UserDto and RoleDto. User has a property which is the RoleDto. In my viewmodel I have the following: ``` public UserDto User { get { return _user; } set { if (_user == value) return; _user = value; User.PropertyChanged += UserPropertyChanged; OnPropertyChanged("User"); } } private UserDto _user; public IEnumerable<RoleDto> Roles { get; set; } //I load all available roles in here ``` In the view, I want to select the role that the user belongs. This is how I define the combobox in the view: ``` <ComboBox Grid.Row="3" Grid.Column="1" Margin="5" ItemsSource="{Binding Roles}" SelectedItem="{Binding User.Role, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Description" /> ``` If I try to create a new user and select a role from the combobox, it is correctly binded to the user. The problem is that when I load a user that already exists, the role is not displayed in the combobox (even the user has a role defined). Any help please? Thanks in advance

Original source

Related problems