wpfsilverlightxamlselecteditemselectedvalue

Difference between SelectedItem, SelectedValue and SelectedValuePath


What is the difference betweeen the following:

All these dependency properties are defined in Selector class. I often confuse SelectedItem with SelectedValue , and SelectedValue with SelectedValuePath.

I would like to know the difference between them, and also when do we use them, especially SelectedValue and SelectedValuePath. Please explain their use with some simple examples.


Solution

  • Their names can be a bit confusing :). Here's a summary:

    The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).

    <ComboBox ItemsSource="{Binding Categories}" 
              SelectedValue="{Binding CategoryID, Mode=TwoWay}" 
              SelectedValuePath="ID" 
              DisplayMemberPath="Name" />
    
    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    
    public class Product
    {
        public int CategoryID { get; set; }
    }
    

    It's a little confusing initially, but hopefully this makes it a bit clearer... :)

    Chris