Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
Joan Venge Avatar asked May 17 '11 22:05

Joan Venge


1 Answers

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

like image 194
J Cooper Avatar answered Nov 11 '22 07:11

J Cooper