user2025830
user2025830

Reputation: 902

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?

Upvotes: 2

Views: 1859

Answers (2)

bic
bic

Reputation: 2281

You can use AttachedCommandBehavior to do this.

Upvotes: -1

Florian Gl
Florian Gl

Reputation: 6014

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}" 

Upvotes: 2

Related Questions