I have a typical tree view and viewmodel. The viewmodel has an observable collection of other models that serve as a data source for the tree.
public class TreeViewVM { public ObservableCollection<ItemVM> Items { get; private set; } public ItemVM SelectedItem { get; set; } }
and ItemVM:
public class ItemVM { public string Name { get; set; } public ImageSource Image { get; private set; } public ObservableCollection<ItemVM> Children { get; private set; } public ICommand Rename { get; private set; } }
View:
<TreeView Selecteditem="{Binding SelectedItem}" ItemsSource="{Binding Items}"> <TreeView.ItemTemplate> <HierarchicalDataTemplate> <StackPanel Orientation="Horizontal"> <StackPanel.InputBindings> <KeyBinding Key="F2" Command="{Binding Rename}"/> </StackPanel.InputBindings> <Image Source="{Binding Image}"/> <TextBlock Text="{Binding Name}"/> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView>
However, my command will not be called no matter what I try, while it is inside the "HierarchicalDataTemplate".
If I moved KeyBinding to TreeView.InputBindings (and ICommand / RelayCommand from ItemVM to TreeViewVM), everything will be fine, the command will be called.
But I would like to have a command in ItemVM (as it makes sense). Any ideas?
wpf key-bindings treeview treeviewitem
Andrei Rรฎnea
source share