Joan Venge
Joan Venge

Reputation: 330912

How to disable double click behaviour in a WPF TreeView?

In my TreeView, I have different events for MouseDown/MouseUp, etc but when I do it fast enough the TreeView expands/collapses the TreeNode. I don't want this baked-in behaviour.

Is there a way to disable this?

Upvotes: 14

Views: 12201

Answers (2)

RonnyR
RonnyR

Reputation: 230

If you want to prevent the expanding/collapsing of the TreeView on DoubleClick, but at the same time use a command for this event, you could use this solution:

https://stackoverflow.com/a/60869105/1206431

Upvotes: 0

J Cooper
J Cooper

Reputation: 4988

You could suppress the double click event of TreeViewItem like so:

xaml:

<TreeView DockPanel.Dock="Left" TreeViewItem.PreviewMouseDoubleClick="TreeViewItem_PreviewMouseDoubleClick">
    <TreeViewItem Header="Node Level 1" IsExpanded="True" >
        <TreeViewItem Header="Node Level 2.1" >
            <TreeViewItem Header="MyItem" />
        </TreeViewItem>
        <TreeViewItem Header="Node Level 2.2">
            <TreeViewItem Header="MyItem" />
        </TreeViewItem>
    </TreeViewItem>
</TreeView>

code:

private void TreeViewItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    //this will suppress the event that is causing the nodes to expand/contract 
    e.Handled = true;
}

UPDATE

According to msdn docs:

Although this routed event seems to follow a tunneling route through an element tree, it actually is a direct routed event that is raised along the element tree by each UIElement... Control authors who want to handle mouse double clicks should use the PreviewMouseLeftButtonDown event when ClickCount is equal to two. This will cause the state of Handled to propagate appropriately in the case where another element in the element tree handles the event.

I'm not sure if this why you are having issues or not, but we'll do it the MSDN way and use PreviewMouseLeftButtonDown instead:

xaml:

<TreeView DockPanel.Dock="Left" TreeViewItem.PreviewMouseLeftButtonDown="TreeView_PreviewMouseLeftButtonDown">
    <TreeViewItem Header="Node Level 1" IsExpanded="True">
        <TreeViewItem Header="Node Level 2.1" >
            <TreeViewItem Header="MyItem" />
        </TreeViewItem>
        <TreeViewItem Header="Node Level 2.2">
            <TreeViewItem Header="MyItem" />
        </TreeViewItem>
    </TreeViewItem>
</TreeView>

code:

private void TreeView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (e.ClickCount > 1)
    {
        //here you would probably want to include code that is called by your
        //mouse down event handler.
        e.Handled = true;
    }
}

I've tested this and it works no matter how many times i click

Upvotes: 20

Related Questions