Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF expand TreeView on single mouse click

I have a WPF TreeView with a HierarchicalDataTemplate.

Currently I have to double click an item to expand/collapse it.

I would like to change this behaviour to a single click, without loosing other functionality. So it should expand and collapse on click.

What is the recommended way to do this?

Thanks!

like image 771
SaphuA Avatar asked Mar 04 '11 14:03

SaphuA


2 Answers

You could use a re-templated checkbox as your node (containing whatever template you are currently using) with its IsChecked property bound to the IsExpanded property of the TreeViewItem.

Here is a template I've just test that seems to do the job:

<HierarchicalDataTemplate ItemsSource="{Binding Items}">
    <CheckBox IsChecked="{Binding RelativeSource={RelativeSource AncestorType=TreeViewItem}, Path=IsExpanded}">
        <CheckBox.Template>
            <ControlTemplate>
                <TextBlock Text="{Binding Header}"></TextBlock>
            </ControlTemplate>
        </CheckBox.Template>
    </CheckBox>
</HierarchicalDataTemplate>

Just replace the ControlTemplate contents with whatever you need.

like image 150
Darren Avatar answered Sep 20 '22 14:09

Darren


If you are using a standard TreeViewItem, then you can capture the click event:

private void OnTreeViewMouseUp( object sender, MouseButtonEventArgs e )
{
    var tv = sender as TreeView;
    var item = tv.SelectedItem as TreeViewItem;

    if( item != null )
        item.IsExpanded = !item.IsExpanded;

    e.Handled = true;
}

private void OnTreeViewPreviewMouseDoubleClick( object sender, MouseButtonEventArgs e )
{
    e.Handled = true;
}

Most likely in your case, you'll need to do something with your binding and ViewModel. Here's a good article from CodePlex: Simplifying the WPF TreeView by Using the ViewModel Pattern.

like image 29
Metro Smurf Avatar answered Sep 21 '22 14:09

Metro Smurf