Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand WPF TreeView on single click of item

Tags:

wpf

treeview

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?

like image 560
AKoran Avatar asked May 27 '10 14:05

AKoran


People also ask

How to expand TreeView in wpf?

To expand a treeview item you need to set the IsExpanded attribute to True. Conversely, in order to collapse an item you should set the IsExpanded attribute to False. The default value of the IsExpanded property is False.

What is TreeView in WPF?

The TreeView control provides a way to display information in a hierarchical structure by using collapsible nodes. This topic introduces the TreeView and TreeViewItem controls, and provides simple examples of their use.


2 Answers

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!

like image 165
BJennings Avatar answered Nov 16 '22 01:11

BJennings


Maybe is not the most elegant solution but this works:

    static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
    {
        while (source != null && source.GetType() != typeof(T))
            source = VisualTreeHelper.GetParent(source);

        return source;
    }

then in the TreeViewItem.Selected Handler:

        private void Treeview_Selected(object sender, RoutedEventArgs e)
        {
            var treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
            if (treeViewItem != null) treeViewItem.IsExpanded = true;
        }

the VisualUpwardSearch magic is taken from here: Select TreeView Node on right click before displaying ContextMenu

Regards

like image 41
Marcote Avatar answered Nov 16 '22 02:11

Marcote