79

I have always struggled with those comboBox properties

  1. DisplayMemberPath
  2. SelectedValue
  3. SelectedValuePath

I am building a master detail form .

  1. ComboBox filled with Customers
  2. User Selects a Customer in Combo
  3. All the textBoxes EG Fills correctly

The problem I am having I have made it work but I don't understand those properties and the differences. Is there a noddy example explaining what they do?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
user451259
  • 1,003
  • 2
  • 12
  • 13

1 Answers1

165

I think we can understand this better with an example. See this class:

public class Employee
{
   public int Id { get; set; }
   public string Name { get; set; }
}

and the following xaml:

<ComboBox ItemsSource="{Binding Source={StaticResource Employees}}"
          DisplayMemberPath="Name"
          SelectedValuePath="Id"/>

DisplayMemberPath points to the Name property, so the value displayed in the ComboBox and the Employee entries contained in the drop down list, will be the Name property of the Employee object.

To understand the other two, you should first understand SelectedItem. SelectedItem will return the currently selected Employee object from the ComboBox. You can also assign SelectedItem with an Employee object to set the current selection in the ComboBox.

SelectedValuePath points to Id, which means you can get the Id of currently selected Employee by using SelectedValue. You can also set the currently selected Employee in the ComboBox by setting the SelectedValue to an Id (which we assume will be present in the Employees list).

Yogesh
  • 14,498
  • 6
  • 44
  • 69
  • 11
    This is the most concise and easiest to understand explanation of these concepts that I've seen. – JoelWilson Mar 13 '14 at 22:15
  • 1
    NB: This sample would not work, because `Id` and `Name` have to be properties, not class fields. – Shorstok Aug 04 '16 at 11:04
  • 3
    You are right. The class was just meant to show pseudo code. Fixed it. – Yogesh Aug 04 '16 at 12:57
  • @Yogesh IMO, `for me`, this is better, more concise and easier to understand than [this answer](https://stackoverflow.com/a/4902454/1232087). I said `for me` since we all have different ways of understanding things. Maybe, the other answer is better to understand for some other readers. – nam Aug 21 '20 at 04:09