How to: Use SelectedValue, SelectedValuePath, and SelectedItem

This example shows how to use the SelectedValue and SelectedValuePath properties to specify a value for the SelectedItem of a TreeView.


The SelectedValuePath property provides a way to specify a SelectedValue for the SelectedItem in a TreeView. Typically, a SelectedItem represents a data item in a collection and displays a component of that data item. The SelectedValuePath property specifies the component to use in order to set the SelectedValue property. The component that you specify for the SelectedValuePath property may be different from the component that is displayed by the SelectedItem. The examples in this topic illustrate this concept.

The following example shows an XmlDataProvider that contains employee information.

<XmlDataProvider x:Key="myEmployeeData" XPath="/EmployeeData">
    <EmployeeData xmlns="">
        <EmployeeName>Jesper Aabergy</EmployeeName>
        <EmployeeName>Dominik Paiha</EmployeeName>

The following example defines a HierarchicalDataTemplate that specifies the components of the employee information that appears in a TreeViewItem control. Note that the HierarchicalDataTemplate does not specify the EmployeeNumber as part of the template.

<HierarchicalDataTemplate DataType="EmployeeInfo" 
  ItemsSource ="{Binding XPath=EmployeeWorkDay}">
  <TextBlock Text="{Binding XPath=EmployeeName}" />

The following example shows a TreeView that uses the HierarchicalDataTemplate to display the EmployeeName and EmployeeWorkDay information and that sets the SelectedValue property to the EmployeeNumber. When you select an EmployeeName in the TreeView, the SelectedItem property returns the EmployeeInfo data item that corresponds to the selected EmployeeName. However, because the SelectedValuePath of this TreeView is set to EmployeeNumber, the SelectedValue is set to the EmployeeNumber.

<TreeView ItemsSource="{Binding Source={StaticResource myEmployeeData}, 

For the complete sample, see TreeView that Specifies SelectedValuePath.

See Also