1

is there a way to use commands in a treeview with a HierarchicalDataTemplate, so that i can react on the click on an item in the treeview? i would prefer a solution without code-behind if there is one.

Here is my TreeView:

<TreeView ItemsSource="{Binding Main.TreeItems}">
    <TreeView.ItemTemplate>                     
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
            <TextBlock Text="{Binding Path=Header}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>                
</TreeView>
user2025830
  • 872
  • 2
  • 17
  • 37

1 Answers1

0

provide an property of type ICommand on your Item (ViewModel) and Bind to that. So your item class would be something like:

class MyTreeItem
{
   public MyTreeItem()
   {
      this.SomeCommand = /* create command here */ null;
      this.Children = new ObservableCollection<MyTreeItem>();
   }

   public ICommand SomeCommand { get; private set; }

   public ObservableCollection<MyTreeItem> Children { get; private set; }
}

In xaml you can then write:

<TreeView ItemsSource="{Binding Main.TreeItems}">
    <TreeView.ItemTemplate>                     
       <HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
            <TextBlock Text="{TemplateBinding Header}" />
            <Button Text="My Command" Command="{TemplateBinding SomeCommand}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>                
</TreeView>

I think that should work, at least it did similarily last time i used that :)

Philipp Aumayr
  • 1,400
  • 11
  • 14
  • ok on the button i can use the command property. but thats not nice to have buttons in the treeview. ;-) is there a way to do that on the click on the textblock? – user2025830 Feb 15 '13 at 07:18
  • http://stackoverflow.com/questions/7003507/how-to-a-add-a-command-to-a-wpf-textblock is probably what you are looking for :) – Philipp Aumayr Feb 15 '13 at 07:51
  • thats a good solution and it works well if my textblock is not in the treeview. but for my problem it doesn't work if the textblock element is used in the treeview. any idea why? – user2025830 Feb 15 '13 at 08:41
  • are you sure you are using a template binding? – Philipp Aumayr Feb 15 '13 at 12:11
  • templatebinding is not available for the mousebinding and i don't want to use the button in a treeview – user2025830 Feb 15 '13 at 12:28
  • you could also restyle the button? from a control perspective what you are doing is changing the appearance of a button. – Philipp Aumayr Feb 15 '13 at 12:29