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. The SelectedItem represents an object in the Items collection and the TreeView displays the value of a single property of the selected item. The SelectedValuePath property specifies the path to the property that is used to determine the value of the SelectedValue property. 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 displays the EmployeeName and EmployeeWorkDay of the Employee. 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 previously defined HierarchicalDataTemplate 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}, 

<TextBlock Margin="10">SelectedValuePath: </TextBlock>
<TextBlock Margin="10,0,0,0" 
           Text="{Binding ElementName=myTreeView, 

<TextBlock Margin="10">SelectedValue: </TextBlock>
<TextBlock Margin="10,0,0,0" 
           Text="{Binding ElementName=myTreeView, 

See Also

TreeView Overview
How-to Topics