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.

Example

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">
  <x:XData>
    <EmployeeData >
      <EmployeeInfo>
        <EmployeeName>Jesper Aabergy</EmployeeName>
        <EmployeeWorkDay>Monday</EmployeeWorkDay>
        <EmployeeWorkDay>Wednesday</EmployeeWorkDay>
        <EmployeeWorkDay>Friday</EmployeeWorkDay>
        <EmployeeStartTime>8:00am</EmployeeStartTime>
        <EmployeeNumber>12345</EmployeeNumber>
      </EmployeeInfo>
      <EmployeeInfo>
        <EmployeeName>Dominik Paiha</EmployeeName>
        <EmployeeWorkDay>Monday</EmployeeWorkDay>
        <EmployeeWorkDay>Tuesday</EmployeeWorkDay>
        <EmployeeStartTime>6:30am</EmployeeStartTime>
        <EmployeeNumber>98765</EmployeeNumber>
      </EmployeeInfo>
    </EmployeeData>
  </x:XData>
</XmlDataProvider>

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}" />
</HierarchicalDataTemplate>

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}, 
    XPath=EmployeeInfo}" 
    Name="myTreeView" 
    SelectedValuePath="EmployeeNumber" 
    />

For the complete sample, see TreeView that Specifies SelectedValuePath.

See Also

Reference

TreeView
TreeViewItem

Concepts

TreeView Overview

Other Resources

TreeView How-to Topics
TreeView Samples