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?
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.
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.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With