sadrick
sadrick

Reputation: 13

ComboBox binding with DisplayMemberPath and SelectedValuePath does not work as expected

I bind an ObservableCollection to a ComboBox and set the DisplayMemberPath to the Name, with the help of SelectedValuePath I wanted to achieve that Device.ObjectId gets the value of Object.Id. But this doesn't seem to work, the Object.Name is still set for Device.ObjectId. How do I get the ComboBox to show the Name but set the Id?

public class Object
{
        public string Id { get; set; }
        public string Name { get; set; }
}

ObservableCollection Objects = new ObservableCollection<Object>();
    
    
<ComboBox ItemsSource="{Binding Objects}" DisplayMemberPath="Name" SelectedValuePath="Id">
    <ComboBox.Text>
        <Binding Path="Device.ObjectId" UpdateSourceTrigger="PropertyChanged">
    </ComboBox.Text>
</ComboBox>

Upvotes: 0

Views: 689

Answers (1)

Jesse Good
Jesse Good

Reputation: 52395

Since you set the SelectedValuePath attribute to Id, you can bind to the SelectedValue attribute to get the value. Something like this:

<ComboBox ItemsSource="{Binding Objects}" DisplayMemberPath="Name"
          SelectedValuePath="Id" SelectedValue="{Binding Device.ObjectId}" />

Upvotes: 1

Related Questions