Search code examples
wpfxamltreeviewmousekey-bindings

Mousebinding in a WPF TreeView


Is there a way to do a Mouse- or KeyBinding in a WPF treeview?

<TreeView ItemsSource="{Binding Main.TreeItems}">
    <TreeView.ItemTemplate>                           
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">                          
            <TextBlock Text="{Binding Path=Header}">
                <TextBlock.InputBindings>
                    <MouseBinding Command="{Binding TreeViewClickCommand}" MouseAction="LeftDoubleClick"/>
                </TextBlock.InputBindings>
             </TextBlock>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

This doesn't work. If i use my Command on a button not in the treeview then the command is fired. How can i solve this problem?


Solution

  • If this Command works outside the TreeView, I assume your TreeViewClickCommand is located in the DataContext of your Window/UserControl.

    Use AncestorType to refer to the TreeViews DataContext (which is the same as the Windows DC, if you did not set it manuelly):

    Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type TreeView}}, Path=DataContext.TreeViewClickCommand}"