Share via


Setting TreeView SelectedItem in Code

It is possible to set the selected item of a TreeView control in WPF without direct interaction with UI elements by including IsSelected property in your data object and binding it to IsSelected property of TreeViewItem. The code snippets below indicate how to set expanded and selected items of a TreeView control by updating the data that is bound to UI element.

- Define the style for TreeViewItem so that IsSelected and IsExpanded properties are bound to corresponding properties on the data:

Code Snippet:

<TreeView x:Name="TreeViewControl" ItemsSource="{Binding}">

    <TreeView.Resources>

        <HierarchicalDataTemplate DataType="{x:Type local:Item}" ItemsSource="{Binding Path=SubItems}">

          <TextBlock Text="{Binding Path=Name}"/>

        </HierarchicalDataTemplate>

        <Style TargetType="TreeViewItem">

            <Setter Property="IsSelected" Value="{Binding Path=IsSelected}"/>

            <Setter Property="IsExpanded" Value="{Binding Path=IsExpanded}"/>

        </Style>               

    </TreeView.Resources>

</TreeView>

 

- Define the Properties in your data class:

Code Snippet:

public class Item : INotifyPropertyChanged

{

    private string name;

    private bool isSelected;

    private bool isExpanded;

    public bool IsExpanded

    {

        get

        {

            return isExpanded;

        }

        set

        {

            isExpanded = value;

            this.OnPropertyChanged("IsExpanded");

        }

    }

    public bool IsSelected

    {

        get

        {

            return isSelected;

        }

        set

        {

            isSelected = value;

            this.OnPropertyChanged("IsSelected");

        }

    }

}

 

- Set the values in the Loaded method so that parent node is expanded and child node is selected when the treeview is displayed.

Code Snippet:

void Window1_Loaded(object sender, RoutedEventArgs e)

{

ObservableCollection<Item> items = new ObservableCollection<Item>();

Item item1 = new Item() {Name = "Item1"};

item1.SubItems.Add(new Item() {Name="Item1_1"});

items.Add(item1);

this.TreeViewControl.DataContext = items;

// Expand parent node and select the child node

item1.IsExpanded = true;

item1.SubItems[0].IsSelected = true;

}

 SettingTreeViewSelectedItemInCode