Wpf – How to expand WPF TreeView on single click of item

treeviewwpf

Right now you have to double click or click the + icon. Is there any way to make it so if a user clicks anywhere on the node it expands?

Best Answer

I had this same problem and found a good solution thanks to another StackOverflow post.

In the control.xaml's TreeView element, you can hook directly into the TreeViewItem's Selected event:

<TreeView ItemsSource="{StaticResource Array}" TreeViewItem.Selected="TreeViewItem_Selected"/>

Then in your control.xaml.cs code behind, you can grab that selected TreeViewItem from the RoutedEventArgs and set it to IsExpanded:

private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
{
    TreeViewItem tvi = e.OriginalSource as TreeViewItem;

    if (tvi == null || e.Handled) return;

    tvi.IsExpanded = !tvi.IsExpanded;
    e.Handled = true;
}

Nice and clean. Hopefully that helps someone!